Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Copy an Array in Go Using Assignment or copy

Copy every element with array assignment, copy part of an array with slice expressions, and see when a pointer shares the original.

Table of Contents

In Go, assign one array to another to copy the whole array. The destination must accept the source’s array type, including its length. To copy only part of an array or copy between arrays of different lengths, pass slices to the built-in copy function.

How to copy one array into another array in Golang Picture 1

Copy an entire array with assignment

package main

import "fmt"

func main() {
    source := [5]int{10, 20, 30, 40, 50}
    destination := source
    destination[0] = 99
    fmt.Println(source)      // [10 20 30 40 50]
    fmt.Println(destination) // [99 20 30 40 50]
}

If the elements are pointers, maps or slices, assignment copies those element values. The referenced data may still be shared.

Copy part of an array

source := [5]int{10, 20, 30, 40, 50}
var destination [3]int
count := copy(destination[:], source[1:])
// destination is [20 30 40]; count is 3.

copy copies as many elements as fit in both slice lengths and returns that count. Use a loop with range if you also need to transform each element as you assign it.

Use a pointer to share the original array

alias := &source gives you another way to address the same array. Writing alias[0] = 99 changes source[0]. Use ordinary assignment when you need a separate array. See the Go specification for array types and copy.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.