Keyed Array Initialization in Go
In Go, array initialization can be enhanced with keyed elements. This technique allows specifying specific indexes for values, offering several advantages:
Compact Initialization
Arrays with many zeros can be initialized concisely using keys. For example:
a := [...]int{5, 4: 1, 2: 3, 0, 1: 4}
This efficiently sets non-zero values at specific indexes, while leaving the remaining untouched.
Skipping Elements
Keys can "jump over" contiguous parts when enumerating elements. Unspecified indexes are automatically filled with zero values:
b := []int{10, 20, 30, 99: 0}
This creates an array of length 100, setting the first three elements and leaving the rest as zeros.
Custom Length Specification
Keys allow specifying the length of an array, while still setting only a few initial elements:
c := []int{10, 20, 30, 99: 0} // Length is 100
Example: Vowel Detection
A compact way to initialize an array for vowel detection:
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
Example: Day of the Week
Similarly, a slice can be used to represent days of the week, marking weekends:
weekend := []bool{5: true, true} // Weekend is Saturday and Sunday
The above is the detailed content of How Can Keyed Array Initialization Simplify Array Creation in Go?. For more information, please follow other related articles on the PHP Chinese website!