Go Arrays: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
=External=
=Internal=
=Internal=



Revision as of 00:44, 28 March 2016

External

Internal

Overview

An array is a numbered sequence of elements, of a single type, and with a fixed length. The length of the array is part of the type name, arrays with different lengths are different types, even if the element type is the same. Arrays are rarely used in Go code, slices are used instead.

Declaration

var a [5]int

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

Type inference and initialization declaration (note that the type inference declaration is invalid for arrays if the length and type is not followed by the initialization literal { ... }, the initialization literal is required):

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

Array Literals

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

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.

Array Length

len() returns the length of the array.