Go Arrays

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

An array is a numbered sequence of elements, of a single type, and with a fixed length. The type can be a Go built-in type or an user type. 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. Arrays are rarely used in Go code, slices are used instead.

Declaration

Long Declaration

var a [5]int

A declaration without explicit initialization initializes the array with the type's zero value.

Long declaration with explicit initialization with an array literal:

var b [3]int = [3]int{1, 2, 3}

Short Declaration

The short declaration:

a := [3]int{1, 2, 3}

The short declaration is invalid for arrays if the length and type is not followed by the initialization literal { ... }, the initialization literal is required.

a := [3]int{
        1, 
        2, 
        3, 
   }

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.

Array Operators and Functions

Indexing Operator

Indexing operator [] returns the value at that position. Accesses are bound-checked and an attempt to access an element out of bounds produces a compile-time or runtime error:

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

Array Length

len() returns the length of the array.