In order to copy a slice in Golang, you can use copy(dst, src) function. This function works on the minimum length of dst
and src
. So, if you want to copy the entire source slice, you need to have destination slice at least as large as source. You may also use append() method.
Code Examples
We will provide you few code examples here.
1. Using make()
to create destination array
arr := []int{1, 2, 3} tmp := make([]int, len(arr)) copy(tmp, arr) fmt.Println(tmp) fmt.Println(arr)
Output –
[1 2 3] [1 2 3]
We use make()
function to create an empty destination slice of equal length as of source. This is important because copy function only runs over minimum length of provided slices.
2. Using append()
arr := []int{1, 2, 3} tmp := append([]int(nil), arr...) fmt.Println(tmp) fmt.Println(arr)
Output –
[1 2 3] [1 2 3]
In this approach there is a caveat. If the slice is big, append will allocate excess memory. To resolve this issue you may use the next solution.
3. Efficient append()
arr := []int{1, 2, 3} tmp := append(make([]int, 0, len(arr)), arr...) fmt.Println(tmp) fmt.Println(arr)
Output –
[1 2 3] [1 2 3]
4. Another append() approach
arr := []int{1, 2, 3} tmp := append(arr[:0:0], arr...) fmt.Println(tmp) fmt.Println(arr)
In this approach tmp
will be nil if arr
is nil. There is no need to declare an empty dst
of type T.