Go Arrays: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 16: Line 16:
A declaration without explicit initialization initializes the array with the [[Go Concepts - The Type System#Zero_Value|type's zero value]].
A declaration without explicit initialization initializes the array with the [[Go Concepts - The Type System#Zero_Value|type's zero value]].


Type inference and initialization declaration:
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 { ... }):


<pre>
<pre>

Revision as of 23:50, 27 March 2016

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 { ... }):

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()