为什么我不能在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).

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...