Home >Backend Development >Golang >How Does Keyed Array Initialization Work in Go?

How Does Keyed Array Initialization Work in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 19:49:11142browse

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:

  • Compact Initialization:
    When an array has numerous zero values and only a few non-zero values, keyed initialization can reduce code length by specifying only the non-zero values.
  • Skipping Elements:
    Keys allow you to "jump over" contiguous parts of the array, leaving the skipped elements with zero values.
  • Specifying First Elements and Length:
    You can define the first few elements of an array while specifying its desired length (max index 1) using keyed initialization.

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}.

  • 5 is assigned to index 0.
  • 1 is assigned to index 4.
  • 0 is assigned to index 5.
  • 3 is assigned to index 2.
  • 2 is assigned to index 3.
  • 4 is assigned to index 1.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn