How to copy one array into another array in Golang

In Golang , an array is a fixed-length sequence containing elements of a specific type. Unlike slices, arrays have a constant size, which is determined when the array is declared. Copying one array to another is simple but requires both arrays to be of the same length and type.

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

For example:

package main import "fmt" // Mảng cơ bản được sử dụng trong tất cả ví dụ var source = [5]int{10, 20, 30, 40, 50} func main() { fmt.Println("Source Array:", source) }

Syntax:

for i := 0; i < len(source); i++ { destination[i] = source[i] }

Use loop to copy an array

Go doesn't provide a built-in copy() function for arrays, so the most common way to copy an array is to iterate through each element and assign that element manually.

Syntax

for i := 0; i < len(source); i++ { destination[i] = source[i] }

For example:

package main import "fmt" var source = [5]int{10, 20, 30, 40, 50} func main() { // Tạo mảng đích có cùng kích thước như mảng nguồn var destination [5]int // Tự tay sao chép từng phần tử for i := 0; i < len(source); i++ { destination[i] = source[i] } fmt.Println("Source:", source) fmt.Println("Destination:", destination) }

Result:

Source: [10 20 30 40 50] Destination: [10 20 30 40 50]

Direct Assignment (Works only with Arrays, Does not work with Slices)

You can assign one array to another if they have the same type and length. This method does not work with slices.

Syntax

destination = source

For example

package main import "fmt" var source = [5]int{10, 20, 30, 40, 50} func main() { // Sao chép bằng cách gán trực tiếp var destination [5]int = source fmt.Println("Source:", source) fmt.Println("Destination:", destination) }

Result

Source: [10 20 30 40 50] Destination: [10 20 30 40 50]

Use Pointers (If Array is Large)

If you are working with large arrays and want to avoid copying, you can use a pointer to refer to the source array. This will not create a new array but will point to the memory location of the existing array.

Syntax

destination = &source

For example

package main import "fmt" var source = [5]int{10, 20, 30, 40, 50} func main() { // Tạo một con trỏ tới mảng nguồn var destination *[5]int = &source fmt.Println("Source:", source) fmt.Println("Destination Array via pointer:", *destination) }

Result

Source: [10 20 30 40 50] Destination Array via pointer: [10 20 30 40 50]

Note:

  1. Direct assignment only works with arrays of the same type and length. If you try to assign arrays of different sizes or types, you will get a compile error.
  2. Using a pointer does not create a new array; it just references the existing array.
4 ★ | 2 Vote

May be interested