How to Make a Shallow Copy of a Slice in Go

Created
Modified

Using append Function

You could write one simple statement to make a shallow copy of a slice.

The following example should cover whatever you are trying to do:

package main

import "fmt"

type T int

func main() {
  a := []T{1, 2}
  
  b := append([]T(nil), a...)
  fmt.Println(a, b)
  b[1] = 4
  fmt.Println(a, b)
}
[1 2] [1 2]
[1 2] [1 4]

Using copy Function

See the following example:

package main

import "fmt"

type T int

func main() {
  a := []T{1, 2}

  b := make([]T, len(a))
  copy(b, a)
  fmt.Println(a, b)
  b[1] = 4
  fmt.Println(a, b)
}
[1 2] [1 2]
[1 2] [1 4]

Related Tags