How to assign values to arrays in Golang?
There are two ways to assign values to arrays in Go language.
- The first element of the array is set to 10.
var arr [5]int
arr[0] = 10
- arr is an array of size 3 with elements 1, 2, and 3.
arr := [3]int{1, 2, 3}
It is important to note that the length of the initialization list must match the length of the array, otherwise a compilation error will occur. If the length of the initialization list is smaller than the array’s length, the remaining array elements will be initialized with default values; if the length of the initialization list is greater than the array’s length, a compilation error will be triggered.
Additionally, you can use […] to let the compiler automatically infer the length of an array based on the size of the initialization list. For example, to create an array containing 1, 2, and 3, you can use arr := […]int{1, 2, 3}. This method allows you to omit the length of the array and let the compiler determine it based on the size of the initialization list.