Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 726
mori Avatar asked Oct 19 '25 05:10

mori


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!