Skip to content
Openweb edited this page Oct 5, 2020 · 6 revisions

Go Arrays

An array is fixed-length sequence of zero of more elements of a particular type. Some salient features:

  1. It is of fixed length.
  2. Two same length arrays can be assigned, compared (== and !=) if underlying types are comparable.
  3. Since arrays are comparable they can be used as keys in maps.
  4. Arrays are passed by copy NOT by reference as in C. Check if these are efficient for your use-cases.
  5. Arrays can not be declared constants, as they are evaluated during runtime not compile time.

Language Constructs

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.

Initialization

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"} 
  1. Go play using Arrays as map keys.
  2. Go play array passed as copy.
Clone this wiki locally