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.

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

报告相同问题?