dongmen1860 2015-05-12 05:33
浏览 95
已采纳

为什么不能用`copy()`复制切片?

I need to make a copy of a slice in Go and reading the docs there is a copy function at my disposal.

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

But when I do:

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

My tmp is empty as it was before (I even tried to use arr, tmp):

[]
[1 2 3]

You can check it on go playground. So why can not I copy a slice?

  • 写回答

5条回答 默认 最新

  • duanchi6377 2015-05-12 05:40
    关注

    The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

    So if your dst is empty (len(dst) == 0), nothing will be copied.

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

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

    Output (as expected):

    [1 2 3]
    [1 2 3]
    

    Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

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

    Edit:

    Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线