微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我不能在golang中复制一个带有拷贝的片段?

我需要复制一个片段,阅读文档中有一个 copy功能在我的支配。

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).

但是当我做

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

我的tmp是空的,就像以前一样(我甚至尝试使用arr,tmp):

[]
[1 2 3]

你可以在playground上查看。那么为什么我不能复制一个片?

内置的 copy(dst,src)拷贝min(len(dst),len(src))元素。

所以如果你的dst是空的(len(dst)== 0),没有任何东西被复制。

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

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中有记录:

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

编辑:

最后,copy()的文档已经被更新,现在它包含了这样一个事实:源和目的地的最小长度将被复制:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐