Copying slices in Go

As we know, Go slices hover on top of fixed arrays; modifying elements in a slice also modifies the underlying array. In some scenarios, that’s unacceptable. Hence, we need slice copying!

1. Use slices.Clone

slices.Clone is available from Go 1.21 onward. What’s cool about it is that it takes care of the pre-allocation of space in memory too — if the built-in copy function has screwed you over before, you’ll appreciate this.

Go
import "slices"

func main() {
    src := []string{"Apple", "Banana", "Cherry"}

    dst := slices.Copy(s)
}

2. Use built-in copy Function

This is everyone’s first girlfriend who gave more pain than pleasure. The thing about copy is you have to allocate memory for the destination slice before calling it. How would anyone find out?

Go
func main() {
    src := []string{"Apple", "Banana", "Cherry"}

    dst := make([]string, len(src))
    
    copy(dst, src)
}

Oh, did I forget to mention in the arguments, destination comes before the source?

3. Cheat with append

This is like using your girlfriend’s shaver. It doesn’t look good in the mirror, but it works more or less the same… actually less performant in some ways.

Go
func main() {
    src := []string{"Apple", "Banana", "Cherry"}

    dst := append([]string{}, src...) // use ... to unpack slice
}

Since append is a variadic function, don’t forget to ... unpack the incoming slice.

Lastly, a gentle reminder:

None of these methods handles deep copying.

Leave a comment

Your email address will not be published. Required fields are marked *