4

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?

mori
  • 973
  • 10
  • 11
  • So IIUC, you want a slice of `len(s)` with pointers in it pointing to nil values? If yes, the only job of `copy` is to provide the length of `s`. You're better off just passing the len explicitly and create a new slice. – tj-recess Mar 04 '19 at 02:13

1 Answers1

4

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242