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

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

    The Go Programming Language Specification

    Appending to and copying slices

    The function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of elements copied is the minimum of len(src) and len(dst). As a special case, copy also accepts a destination argument assignable to type []byte with a source argument of a string type. This form copies the bytes from the string into the byte slice.

    copy(dst, src []T) int
    copy(dst []byte, src string) int
    

    tmp needs enough room for arr. For example,

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

    Output:

    [1 2 3]
    [1 2 3]
    

提交回复
热议问题