duancaozen6066 2019-03-03 20:58
浏览 106
已采纳

复制切片指针(指向新值)

I would like to make a copy of a slice containing pointers, such that the pointers in the new slice point to new values: Let's say s is the original slice and c is the copy. Then changing *c[i] should not affect *s[i].

According to this answer, that's not what happens with the usual copy methods.

What's the shortest way to do this?

  • 写回答

1条回答 默认 最新

  • douqiaolong0528 2019-03-03 21:04
    关注

    Use the following code to copy the values:

    c := make([]*T, len(s))
    for i, p := range s {
    
        if p == nil {
            // Skip to next for nil source pointer
            continue
        }
    
        // Create shallow copy of source element
        v := *p
    
        // Assign address of copy to destination.
        c[i] = &v
    }
    

    Run it in the playground.

    This code creates a shallow copy of the value. Depending on application requirements, you may want to deeply copy the value, or if a struct type, one or more fields. The specifics depend on the actual type T and the application requirements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教