golang append() 已评估但未使用
golang append() evaluated but not used
func main(){
var array [10]int
sliceA := array[0:5]
append(sliceA, 4)
fmt.Println(sliceA)
}
Error : append(sliceA, 4) evaluated but not used
我不知道为什么?切片追加操作不是运行...
参考:Appending to and copying slices
在 Go 中,参数按值传递。
典型的 append
用法是:
a = append(a, x)
你需要写:
func main(){
var array [10]int
sliceA := array[0:5]
// append(sliceA, 4) // discard
sliceA = append(sliceA, 4) // keep
fmt.Println(sliceA)
}
输出:
[0 0 0 0 0 4]
希望对您有所帮助。
sliceA = append(sliceA, 4)
append()
returns 包含一个或多个新值的切片。
请注意,我们需要从追加中接受一个 return 值,因为我们可能会得到一个新的切片值。
根据 Go 文档:
The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
因此 'append' 的 return 值将包含带有附加部分的原始切片。
你可以试试这个:
sliceA = append(sliceA, 4)
内置函数append([]type, ...type)
returns一个array/slice类型的,应该赋给你想要的值,而输入array/slice只是一个源.简单地说,outputSlice = append(sourceSlice, appendedValue)
要理解的关键是slice只是底层数组的一个"view"。
您将该视图通过值 传递给追加函数 ,底层数组被修改,最后追加函数的 return 值为您提供底层数组的不同视图。即切片中有更多项目
your code
sliceA := array[0:5] // sliceA is pointing to [0,5)
append(sliceA, 4) // sliceA is still the original view [0,5) until you do the following
sliceA = append(sliceA, 4)
func main(){
var array [10]int
sliceA := array[0:5]
append(sliceA, 4)
fmt.Println(sliceA)
}
Error : append(sliceA, 4) evaluated but not used
我不知道为什么?切片追加操作不是运行...
参考:Appending to and copying slices
在 Go 中,参数按值传递。
典型的 append
用法是:
a = append(a, x)
你需要写:
func main(){
var array [10]int
sliceA := array[0:5]
// append(sliceA, 4) // discard
sliceA = append(sliceA, 4) // keep
fmt.Println(sliceA)
}
输出:
[0 0 0 0 0 4]
希望对您有所帮助。
sliceA = append(sliceA, 4)
append()
returns 包含一个或多个新值的切片。
请注意,我们需要从追加中接受一个 return 值,因为我们可能会得到一个新的切片值。
根据 Go 文档:
The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
因此 'append' 的 return 值将包含带有附加部分的原始切片。
你可以试试这个:
sliceA = append(sliceA, 4)
内置函数append([]type, ...type)
returns一个array/slice类型的,应该赋给你想要的值,而输入array/slice只是一个源.简单地说,outputSlice = append(sourceSlice, appendedValue)
要理解的关键是slice只是底层数组的一个"view"。 您将该视图通过值 传递给追加函数 ,底层数组被修改,最后追加函数的 return 值为您提供底层数组的不同视图。即切片中有更多项目
your code
sliceA := array[0:5] // sliceA is pointing to [0,5)
append(sliceA, 4) // sliceA is still the original view [0,5) until you do the following
sliceA = append(sliceA, 4)