To copy an array in Go, you can use the copy() function or create a new array and copy the elements manually.
In this example,
arr1
with elements.copy(arr2, arr1)
to copy the elements of arr1
into arr2
.copy()
function copies elements from one slice to another and returns the number of elements copied.package main
import "fmt"
func main() {
arr1 := []int{1, 2, 3, 4, 5}
arr2 := make([]int, len(arr1))
copy(arr2, arr1)
fmt.Println("Array 1:", arr1)
fmt.Println("Array 2 (copy of Array 1):", arr2)
}
Array 1: [1 2 3 4 5] Array 2 (copy of Array 1): [1 2 3 4 5]
In this example,
arr1
with elements.arr2
with the same length as arr1
.arr1
to arr2
individually.package main
import "fmt"
func main() {
arr1 := []int{1, 2, 3, 4, 5}
arr2 := make([]int, len(arr1))
for i := range arr1 {
arr2[i] = arr1[i]
}
fmt.Println("Array 1:", arr1)
fmt.Println("Array 2 (copy of Array 1):", arr2)
}
Array 1: [1 2 3 4 5] Array 2 (copy of Array 1): [1 2 3 4 5]
In this tutorial, we learned How to Copy an Array in Go language with well detailed examples.