golang append() evaluated but not used

后端 未结 5 1337
失恋的感觉
失恋的感觉 2021-02-01 12:12
func main(){
     var array [10]int
     sliceA := array[0:5]
     append(sliceA, 4)
     fmt.Println(sliceA)
}

Error : append(sliceA, 4

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 12:42

    The key to understand is that slice is just a "view" of the underling array. You pass that view to the append function by value, the underling array gets modified, at the end the return value of append function gives you the different view of the underling array. i.e. the slice has more items in it

    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)
    

    reference: https://blog.golang.org/slices

提交回复
热议问题