In the Go programming language, arrays can be initialized in several different ways. Arrays are data structures with a fixed length that store elements of the same type. The following are some basic methods for initializing arrays:
1. Initialize Arrays with Default Values
When you declare an array without immediately initializing it, Go fills the array with the zero value of the element type. For example, numeric types default to 0, strings to empty strings, and booleans to false.
govar arr [5]int fmt.Println(arr) // Output: [0 0 0 0 0]
2. Using Array Literals
You can initialize each element of an array during declaration using array literals:
goarr := [5]int{1, 2, 3, 4, 5} fmt.Println(arr) // Output: [1 2 3 4 5]
This method allows you to directly specify the initial values of each element within the curly braces.
3. Specifying Values for Specific Elements
When initializing an array, you can initialize only certain elements; unspecified elements will use the zero value:
goarr := [5]int{1, 3: 2, 4: 10} fmt.Println(arr) // Output: [1 0 0 2 10]
Here, the first element is initialized to 1, the fourth element to 2, and the fifth element to 10. The remaining elements use the default zero value (0 in this example).
4. Initializing Arrays with Loops
If array initialization requires computation or more complex logic, you can use a loop to set each element's value:
govar arr [5]int for i := range arr { arr[i] = i * 2 } fmt.Println(arr) // Output: [0 2 4 6 8]
This method is highly flexible and suitable for cases where array element values need to be computed through an algorithm.
Summary
The above are several common ways to initialize arrays in Go. The choice depends on the specific scenario and requirements. For example, if you know all the initial values of the elements, using array literals is the simplest and most direct approach. If the element values require computation, using a loop is more appropriate.