golang append() evaluated but not used

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:

func main(){      var array [10]int      sliceA := array[0:5]      append(sliceA, 4)      fmt.Println(sliceA) } 

Error : append(sliceA, 4) evaluated but not used

I don't Know why? The slice append operation is not run...

回答1:

Refer: Appending to and copying slices

In Go, arguments are passed by value.

Typical append usage is:

a = append(a, x) 

You need to write:

func main(){     var array [10]int     sliceA := array[0:5]     // append(sliceA, 4)  // discard     sliceA = append(sliceA, 4)  // keep     fmt.Println(sliceA) } 

Output:

[0 0 0 0 0 4] 

I hope it helps.



回答2:

sliceA =append(sliceA, 4) append returns a slice containing one or more new values. Note that we need to accept a return value from append as we may get a new slice value.



回答3:

you may try this:

sliceA = append(sliceA, 4) 

built-in function append([]type, ...type) returns an array/slice of type, which should be assigned to the value you wanted, while the input array/slice is just a source. Simply, outputSlice = append(sourceSlice, appendedValue)



回答4:

Per the Go docs:

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

So the return value of 'append', will contain your original slice with the appended portion.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!