Home >Backend Development >Golang >How Does Keyed Array Initialization Work in Go?
Keyed Array Initialization in Golang
In Golang, array initialization allows the use of keys to specify the index of an element. Unlike directly setting the index, using keys offers several benefits and use cases.
Use Cases:
Rules:
The syntax for keyed initialization in array literals is: [element_key1: element_value1, ..., element_keyN: element_valueN]. Keys must be constant integer expressions.
Elements with keys have their indices assigned by the key. Elements without keys inherit the index of the previous element, starting from zero for the first element.
Example:
Consider the array: a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4}.
The result is [5 4 3 2 1 0], as expected.
Additional Considerations:
Composite literals allow optional keys for elements in arrays and slices. Arrays must specify an explicit length, while slices may have an omitted length, in which case the length is inferred from the number of elements provided.
The above is the detailed content of How Does Keyed Array Initialization Work in Go?. For more information, please follow other related articles on the PHP Chinese website!