本文介绍了是否可以使用特定值初始化slice?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以像在python中那样用全1初始化切片?
Is it possible to initialize an slice with all 1's like in python?
PYTHON:
onesArray = np.ones(5)
onesList = [1]*5
GOLANG
onesSlice := make([]int, 5)
for i:= 0; i < len(onesSlice); i++{
onesSlice[i] = 1
}
有可能做得更好吗?
推荐答案
是的,但是您必须使用其他语法.
Yes but you have to use a different syntax.
oneSlice := []int{1, 1, 1, 1, 1}
它被称为复合文字"
此外,如果有理由进行迭代(例如计算基于循环变量的值或其他内容),则可以使用range
关键字而不是旧式,因为i等于,i小于i ++循环.
Also, if there is reason to iterate (like calculating the values based loop variable or something) then you could use the range
keyword rather than the old school for i is equal to, i is less than, i++ loop.
for i := range onesSlice {
onesSlice[i] = 1
}
这篇关于是否可以使用特定值初始化slice?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!