Go-实战之 Go Copy 的坑


Copy 不会自动扩容

观察三个 demo 即可明白

demo1

package main

import "fmt"

func main() {
        var src, dst []int
        src = []int{1, 2, 3}
        n := copy(dst, src)

        fmt.Printf("the number of copied elements is %d\n", n)
        fmt.Printf("dst = %v\n", dst)
}
the number of copied elements is 0
dst = []

demo2

package main

import "fmt"

func main() {
	var src, dst []int
	src = []int{1, 2, 3}
	dst = make([]int, 0, 3)
	n := copy(dst, src)

	fmt.Printf("the number of copied elements is %d\n", n)
	fmt.Printf("dst = %v\n", dst)
}
the number of copied elements is 0
dst = []

demo3

package main

import "fmt"

func main() {
	var src, dst []int
	src = []int{1, 2, 3}
	dst = make([]int, 3, 3)
	n := copy(dst, src)

	fmt.Printf("the number of copied elements is %d\n", n)
	fmt.Printf("dst = %v\n", dst)
}
the number of copied elements is 3
dst = [1, 2, 3]

结论

由 demo1、demo2、demo3 可知,copy 的个数是 dst 和 src 的较小值

源码

// The copy built-in function copies elements from a source slice into a
// destination slice. (As a special case, it also will copy bytes from a
// string to a slice of bytes.) The source and destination may overlap. Copy
// returns the number of elements copied, which will be the minimum of
// len(src) and len(dst).
func copy(dst, src []Type) int

由此结论也可以知道, copy 不会自动扩容。


如果本文帮助到了你,帮我点个广告可以咩(o′┏▽┓`o)


评论
  目录