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

前端 未结 6 700
情书的邮戳
情书的邮戳 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:13

    If your slices were of the same size, it would work:

    arr := []int{1, 2, 3}
    tmp := []int{0, 0, 0}
    i := copy(tmp, arr)
    fmt.Println(i)
    fmt.Println(tmp)
    fmt.Println(arr)
    

    Would give:

    3
    [1 2 3]
    [1 2 3]
    

    From "Go Slices: usage and internals":

    The copy function supports copying between slices of different lengths (it will copy only up to the smaller number of elements)

    The usual example is:

    t := make([]byte, len(s), (cap(s)+1)*2)
    copy(t, s)
    s = t
    

提交回复
热议问题