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 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理