Initialization of a Two-Dimensional Array with Inferred Length
In a two-dimensional array, we can use the inferred length method to initialize it, just as we did with one-dimensional arrays.
Write the following code in array.go
:
package main
import "fmt"
func main() {
// Automatically initialized to 0
var simpleArray [3][3]int
// Initialize using specified initial values, use default values for the missing elements
var numArray = [...][]int{{1, 2, 3, 3}, {2, 3, 4, 3}, {0}}
// Initialize using specified initial values
var cityArray = [...][2]string{{"Hangzhou", "Chengdu"}, {"Beijing", "Chongqing"}}
fmt.Println(simpleArray) // [[0 0 0] [0 0 0] [0 0 0]]
fmt.Println(numArray) // [[1 2 3 3] [2 3 4 3] [0]]
fmt.Println(cityArray) // [[Hangzhou Chengdu] [Beijing Chongqing]]
}
The above code demonstrates using the inferred length to initialize a two-dimensional array.
The output is the same as the initialization list method.
However, unlike one-dimensional arrays, in the inferred length initialization of a two-dimensional array, the ...
symbol can only exist in the first square brackets.
For example:
var numArray = [...][]int{{1, 2, 3, 3}, {2, 3, 4, 3}}
This code is valid, but the following two variations are incorrect:
var numArray = [][...]int{{1, 2, 3, 3}, {2, 3, 4, 3}}
var numArray = [...][...]int{{1, 2, 3, 3}, {2, 3, 4, 3}}
In addition, let's compare numArray
and cityArray
.
We can see that in cityArray
, we specify the second parameter of the two-dimensional array's size, as shown below:
var cityArray = [...][2]string{{"Hangzhou", "Chengdu"}, {"Beijing", "Chongqing"}}
This means that we specify the size of each sub-array as 2
during initialization.
If the given values are not enough during initialization, the default values of the data type will be used to fill in the missing elements.
If the number of given values exceeds the specified size, an error will occur.