加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:15:12 所属栏目:大数据 来源:网络整理
导读:我需要复制一个片段,阅读文档中有一个 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 an
我需要复制一个片段,阅读文档中有一个 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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读