Go Arrays: Difference between revisions
Line 16: | Line 16: | ||
</pre> | </pre> | ||
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]]. | ||
Long declaration with explicit initialization with an array literal: | |||
<pre> | |||
var b [3]int = [3]int{1, 2, 3} | |||
</pre> | |||
==Short Declaration== | ==Short Declaration== |
Revision as of 04:31, 6 April 2016
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 := [5]int{1, 2, 3, 4, 5}
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 := [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.