Go Arrays: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 67: Line 67:
=Operators=
=Operators=
==Indexing Operator <tt>[]</tt>==
==Indexing Operator <tt>[]</tt>==
Array elements are accessed using the indexing (subscript) operator. Indices are zero-based.
Array elements are accessed, and can be modified using the indexing (subscript) operator. Indices are zero-based. Accesses are bound-checked and an attempt to access an element out of bounds produces a compile-time or runtime error:
 
Compile-time error:
<font size=-2>
./main.go:13: invalid array index 3 (out of bounds for 3-element array)
</font>
 
Runtime error:
<font size=-2>
panic: runtime error: index out of range
</font>
 
=Iterating though Arrays=
=Iterating though Arrays=
Use the <code>[[Go_Keyword_range|range]]</code> [[Go_Language#Keywords|keyword]]. <code>[[Go_Keyword_range|range]]</code> allows to iterate by indices, values or both.
Use the <code>[[Go_Keyword_range|range]]</code> [[Go_Language#Keywords|keyword]]. <code>[[Go_Keyword_range|range]]</code> allows to iterate by indices, values or both.

Revision as of 18:11, 24 August 2023

External

Internal

Overview

An array is a composite type that consists in a fixed-length, contiguous and numbered sequence of elements. All elements of an array have the same type. The type of the elements can be a Go built-in type, a user type or a pointer. *<type> notation is used to declare a pointer array.

The compiler knows the length of the array and the type of its elements at compile time, so it knows how much space to allocate. The length of the array is part of the type name, arrays with different lengths are of different types, even if the element type is the same. Once an array is declared, its type and length cannot be changed.

Arrays are fast: data is maintain in continuous blocks of memory, which keeps them in the CPU caches longer. Index access and arithmetic is fast: the type information and the guarantee that all elements are of same type allows calculating "distance in memory" to find elements. The arrays are the internal data structures used both by slices and maps, and they are rarely used directly in Go code.

Arrays are Values

An array is a value in Go. It can be used in an assignment operation. The variable name denotes the entire array, thus an array can be assigned to other arrays of the same type, which is designated by the length and element type. When an array a2 is assigned to an array a1, the values of a2 are copied across to a1.

In Go, function arguments are passed by value. The fact that arrays are values also has implications on how arrays are passed between functions: by value. A copy of the entire array is made and placed on the stack, regardless of the array's size. For large arrays, this can have performance implications. That is why, passing pointers to arrays is preferred. As a general rule, array should not be used directly in code, use slices instead.

Declaration

The array type includes the size, enclosed in square brackets, followed by the element type. As mentioned above, different size arrays are different types, even if they have the same element type.

var a [7]int

The elements are initialized to zero value of the type the array is composed of, upon declaration:

println(a[0]) // displays 0

Literals

The array literals are predefined values that go into an array and they are used to initialize an array. The type ([3]int) is specified as part of the array literal, so it does not have to be provided in the var syntax, but it can be provided, redundantly.

var a = [3]int{7, 17, 37}

The length of the array, provided between square brackets, must match the number of elements in the literal, otherwise the compiler will indicate compilation error.

A better, alternative representation of the array literal uses [...] to express that the size of the array will be given by the number of elements in the literal.

var a = [...]int{7, 17, 37} // the type of a is inferred to be [3]int

var b = [...]int{
    5,
    15,
    25,
 }

The extra trailing comma is required when the elements are specified on separate lines, but not when they're specified in a single line. This is to allow commenting out elements without breaking the program.

Partial Initialization Literals

Go provides syntax for initializing just some of the elements with specified values, letting the compiler to initialize the rest with zero values:

a := [100]int{0:10, 1:20}

In the example above, the element 0 is initialized to 10, the element 1 is initialized to 20 and the rest are initialized to their zero value (0).

Initialization

The initialization with type inference, with a literal, can be used:

var a = [...]int{7, 17, 37}

Also, the short variable declaration can be used as well:

a := [...]int{7, 17, 37}

Empty Array

Operators

Indexing Operator []

Array elements are accessed, and can be modified using the indexing (subscript) operator. Indices are zero-based. Accesses are bound-checked and an attempt to access an element out of bounds produces a compile-time or runtime error:

Compile-time error:

./main.go:13: invalid array index 3 (out of bounds for 3-element array)

Runtime error:

panic: runtime error: index out of range

Iterating though Arrays

Use the range keyword. range allows to iterate by indices, values or both. Iterate by indices:

for i := range a {
  fmt.Printf("index: %d\n", i)
}

Iterate by values:

for _, e := range a {
  fmt.Printf("element value: %d\n", e)
}

Iterate by both indices and values:

for i, e := range a {
  fmt.Printf("index: %d, element value: %d\n", i, e)
}

TO DISTRIBUTE

[]


Array Length

len() returns the length of the array.

Iterating over Arrays

range Keyword

Multidimensional Arrays

TODO Go in Action page 84.