Why can't I duplicate a slice with `copy()`?

前端 未结 6 806
情书的邮戳
情书的邮戳 2021-01-29 23:02

I need to make a copy of a slice in Go and reading the docs there is a copy function at my disposal.

The copy built-in function copies elements from a so

6条回答
  •  感动是毒
    2021-01-29 23:12

    Another simple way to do this is by using append which will allocate the slice in the process.

    arr := []int{1, 2, 3}
    tmp := append([]int(nil), arr...)  // Notice the ... splat
    fmt.Println(tmp)
    fmt.Println(arr)
    

    Output (as expected):

    [1 2 3]
    [1 2 3]
    

    So a shorthand for copying array arr would be append([]int(nil), arr...)

    https://play.golang.org/p/sr_4ofs5GW

提交回复
热议问题