Go Arrays: Difference between revisions
Line 12: | Line 12: | ||
=Declaration= | =Declaration= | ||
==Long Declaration== | |||
<pre> | <pre> | ||
Line 19: | Line 21: | ||
A declaration without explicit initialization initializes the array with the [[Go Concepts - The Type System#Zero_Value|type's zero value]]. <font color=red>I am not sure how I can explicitly initialize with this syntax.</font> | A declaration without explicit initialization initializes the array with the [[Go Concepts - The Type System#Zero_Value|type's zero value]]. <font color=red>I am not sure how I can explicitly initialize with this syntax.</font> | ||
==Short Declaration== | |||
Short 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''): | |||
<pre> | <pre> |
Revision as of 00:56, 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
Long Declaration
var a [5]int
A declaration without explicit initialization initializes the array with the type's zero value. I am not sure how I can explicitly initialize with this syntax.
Short Declaration
Short 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}
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.