[英]Copy a slice of pointers (pointing to new values)
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.我想复制一个包含指针的切片,以便新切片中的指针指向新值:假设
s
是原始切片, c
是副本。 Then changing *c[i]
should not affect *s[i]
.然后改变
*c[i]
应该不会影响*s[i]
According to this answer , that's not what happens with the usual copy methods.根据这个答案,通常的复制方法不会发生这种情况。
What's the shortest way to do this?执行此操作的最短方法是什么?
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.
具体取决于实际的 T 型和应用要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.