go / expert
Snippet
Sparse Array Initialization via Index-Keyed Composite Literals
Go allows composite array literals to explicitly specify element indices. Unspecified indices are automatically initialized with their zero-value, and using [...] allows the compiler to deduce the exact array length based on the highest index specified.
snippet.go
go
1
2
3
4
5
6
7
8
9
package mainimport "fmt"func main() {matrixRow := [...]int{0: 10, 5: 50, 9: 100}fmt.Printf("Length: %d, Capacity: %d\n", len(matrixRow), cap(matrixRow))fmt.Printf("Values: %#v\n", matrixRow)}
Breakdown
1
matrixRow := [...]int{0: 10, 5: 50, 9: 100}
Allocates a fixed 10-element array where index 0, 5, and 9 are set, while unlisted indices default to 0.
2
fmt.Printf("Length: %d, Capacity: %d\n", len(matrixRow), cap(matrixRow))
Prints array dimensions showing length equals capacity (10).