Arrays

Arrays are container types in golang with a specific type, in a numbered sequence

Arrays are an arrangement of elements in a sequential order. While arrays exist in golang, they are not as commonly used as Slices, which we will cover in the next section. However, here are some example usages of arrays in golang

arrays_basics.go
package main

import "fmt"

func main() {
  // declare an empty int array with size 5
  var arr [5]int
  fmt.Println("empty array:", arr)
  
  // set the element at the 4th index = 23
  arr[4] = 100
  fmt.Println("set:", arr)
  // we can print individual array items using the index
  fmt.Println("get:", arr[4])
  // the len() function allows us to print the length of the array
  fmt.Println("len:", len(a))
  
  // arrays can also be intialized with some values
  arr2 := [5]int{1, 2, 3, 4, 5}
  fmt.Println("with vals:", arr2)
  
  // two dimentional arrays
  var arr_2d [5][7]int
  for i := 0; i < 5; i++ {
    for j := 0; j < 7; j++ {
      arr_2d[i][j] = i + j
    }
  }
  fmt.Println("2D Array: ", arr_2d)
}

Arrays can be declared with any type, not only the int type. Also, arrays in golang are zero-indexed, which means the first item in the array has an index of zero.

We can let the compiler infer the size of the array by using the following syntax:

arr := [...]int{3, 5, 7, 9, 11, 13, 17}

The ellipsis in the square brackets instructs the compiler to infer the size.

Looping through Arrays

We can use a simple for loop to loop through array items, or use range loops. The len() function allows us to get the length of the array.

package main

import "fmt"

func main() {
  fruits := [...]string{"banana", "apple", "orange", "pear", "mango"}
  // two ways to loop through the array
  for i := 0; i < len(fruits); i++ {
    fmt.Println(fruits[i])
  }
  // or we could use a range loop
  for i, fruit := range fruits {
    fmt.Printf("Fruit #%d is %s\n", i, fruit)
  }
}

Last updated