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?
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
}
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.