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

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

    The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

    So if your dst is empty (len(dst) == 0), nothing will be copied.

    Try tmp := make([]int, len(arr)) (Go Playground):

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

    Output (as expected):

    [1 2 3]
    [1 2 3]
    

    Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

    The number of elements copied is the minimum of len(src) and len(dst).

    Edit:

    Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

    Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

提交回复
热议问题