golang append() evaluated but not used

后端 未结 5 1334
失恋的感觉
失恋的感觉 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:39

    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.

提交回复
热议问题