Declare and initialize arrays
Declare and initialize arrays
An array stores a fixed number of elements of one type. [N]T means N elements of type T. Uninitialized elements have their type’s zero value. Use arrays when the number of items is fixed, such as seven daily readings.
package main
import "fmt"
func main() { var a [3]int fmt.Println(a) a = [3]int{12, 15, 18} fmt.Println(a)}[3]int is the type; braces supply initial values in index order. The uninitialized array already contains three zeros.
Expected output:
[0 0 0][12 15 18]Infer length and use keyed literals
package main
import "fmt"
func main() { days := [...]string{"Mon", "Tue", "Wed"} flags := [4]bool{2: true} fmt.Println(len(days), days) fmt.Println(flags)}[...] infers length as the highest initialized index plus one, or zero for an empty literal. The keyed literal sets index 2 to true. Too many elements cause a compile error. An array cannot grow with append.
Expected output:
3 [Mon Tue Wed][false false true false]Try it locally
Create four integers with only index 1 set to 9. Print the array and length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 01: Declare and initialize arrays
Check the lesson objective before moving on.
What is the zero value of [3]int?
What is the length of [...]int{3:7}?