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).@H_404_7@
但是当我做@H_404_7@
arr := []int{1,2,3} tmp := []int{} copy(tmp,arr) fmt.Println(tmp) fmt.Println(arr)
我的tmp是空的,就像以前一样(我甚至尝试使用arr,tmp):@H_404_7@
[] [1 2 3]
你可以在playground上查看。那么为什么我不能复制一个片?@H_404_7@
copy(dst,src)
拷贝min(len(dst),len(src))元素。
所以如果你的dst是空的(len(dst)== 0),没有任何东西被复制。@H_404_7@
尝试tmp:= make([] int,len(arr))(Go Playground):@H_404_7@
arr := []int{1,3} tmp := make([]int,len(arr)) copy(tmp,arr) fmt.Println(tmp) fmt.Println(arr)
[1 2 3] [1 2 3]
不幸的是,这没有记录在builtin
包中,但在Go Language Specification: Appending to and copying slices中有记录:@H_404_7@
The number of elements copied is the minimum of
len(src)
andlen(dst)
.@H_404_7@
编辑:@H_404_7@
最后,copy()的文档已经被更新,现在它包含了这样一个事实:源和目的地的最小长度将被复制:@H_404_7@
Copy returns the number of elements copied,which will be the minimum of len(src) and len(dst).@H_404_7@