-
Notifications
You must be signed in to change notification settings - Fork 3
Arrays
Openweb edited this page Oct 5, 2020
·
6 revisions
An array is fixed-length sequence of zero of more elements of a particular type. Some salient features:
- It is of fixed length.
- Two same length arrays can be assigned, compared (
==
and!=
) if underlying types are comparable. - Since arrays are comparable they can be used as keys in maps.
- Arrays are passed by copy NOT by reference as in C. Check if these are efficient for your use-cases.
- Arrays can not be declared constants, as they are evaluated during runtime not compile time.
You can declare arrays as known sized elements. By Go convention, they are all initialized with zero element type.
var planetGroup, innerPlanets [4]string // Arrays with 4 planets each.
var outerPlanets [4]string
You can access elements using subscript [#]
notation, a valid index from 0
through length - 1
. Go Play with array initialization and access. Note the address of variables. Assignment copies all elements not the pointers.
Array literals notation:
// Declare array of 4 planets
var terrestrialPlanets = [4]string{"Mercury", "Venus", "Earth", "Mars"}
// ellipses ... determine size from number of initializers
var gasPlanets = [...]string{"Jupiter", "Saturn", "Uranus", "Neptune"}
// Ok to compare array of same size and underlying element type, e.g.:
if terrestrialPlanets != gasPlanets {
fmt.Println("terrestrialPlanets != gasPlanets")
}
Example: go play array initialization
You can also use index in literal to denote specific element.
var someNamedPlanets = [8]string{2: "Earth", 5: "Saturn"}