![]() |
VOOZH | about |
In Go, an array is a fixed-length sequence that holds 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 straightforward but requires that both arrays have the same length and type.
package main
import "fmt"
// Basic array to be used in all examples
var source = [5]int{10, 20, 30, 40, 50}
func main() {
fmt.Println("Source Array:", source)
}
for i := 0; i < len(source); i++ {
destination[i] = source[i]
}
Table of Content
Go doesn’t provide a built-in copy() function for arrays, so the most common way to copy an array is by iterating through each element and assigning it manually.
for i := 0; i < len(source); i++ {
destination[i] = source[i]
}
Example
Source: [10 20 30 40 50] Destination: [10 20 30 40 50]
You can assign one array to another if they are of the same type and length. This method doesn’t work with slices.
destination = sourceExample
Source: [10 20 30 40 50] Destination: [10 20 30 40 50]
If you are working with large arrays and want to avoid copying, you can use pointers to reference the source array. This won’t create a new array but will point to the existing array’s memory location.
destination = &sourceExample
Source: [10 20 30 40 50] Destination Array via pointer: [10 20 30 40 50]
Note:
- Direct assignment only works for arrays of the exact same type and length. If you try to assign arrays of different sizes or types, you’ll encounter a compilation error.
- Using pointers doesn’t create a new array; it only references the existing array.