是否可以用特定值初始化切片?

Is it possible to initialize slice with specific values?

是否可以像 python 那样用全 1 初始化切片?

PYTHON:

onesArray = np.ones(5)
onesList = [1]*5

GOLANG

onesSlice := make([]int, 5)
for i:= 0; i < len(onesSlice); i++{
    onesSlice[i] = 1
}

还有比这更好的吗?

是的,但您必须使用不同的语法。

oneSlice := []int{1, 1, 1, 1, 1}

简称为'composite literal'

此外,如果有理由进行迭代(例如计算基于循环变量的值或其他东西),那么您可以使用 range 关键字而不是旧学校,因为 i 等于,i 小于, i++ 循环。

for i := range onesSlice {
    onesSlice[i] = 1
}