Go - Arrays and Slices

Page content


Like any other programming language, arrays in Go are used to group elements of same type and has a fixed length together. Whenever an array is declared or initialized the type of array has to be defined. Type of elements and the length are both used to defined the type of the array. For example, the array below can store string values and it’s length is 4, so its type is [4]string.

var names [4]string

The default values of an array are the Zero values, which is based on the data type of array. In the above array since the data type is string, so the default Zero values in this case will be "" (empty string).

Values can be set like this:


There is another way to define and initialize array in a single statement.

  name := [4]string{"Eeny", "Meeny", "Miny", "Moe"}


  name := [...]string{"Eeny", "Meeny", "Miny", "Moe"}

The three dots will check the number of elements to be added and create the Array of that length.

Once the length of array has been defined, it cannot be changed. An array of size 4 cannot have 5 or more elements.


Slices on the other hand are similar to arrays but with flexible length (also it’s recommended to use Slices over Arrays when grouping data together). Also like Arrays Slices can only have data values of similar type.

Slices are defined using a composite literal, like below.

func main() {
  // s := type{values} // <- composite literal
  s := []int{1, 2, 3, 4}

Trying to add an element which is not of the type that Go is expecting, will result in an error.

func main() {
  s := []int{1, 2, "hi", 3, 4}

Error: cannot use "hi" (type untyped string) as type int in slice literal

Loop (for range)

To loop over the elements of Array/Slice, for range method can be used. It returns the current index and the value stored at that index.

import "fmt"

func main() {
  s: = []int{100, 22, 13, 95}

  for i, v := range s {
    fmt.Println(i, v)

0 100
1 22
2 13
3 95

Slicing from a slice

There are few ways to print the whole content of a slice.

import "fmt"

func main() {
  s := []int{10, 20, 30, 40}

  // 1. get each element one at a time via their index value
	fmt.Println(s[0]) // 10
	fmt.Println(s[1]) // 20
	fmt.Println(s[2]) // 30
	fmt.Println(s[3]) // 40

  // 2. by simply printing out the slice
  fmt.Println(s) // [10 20 30 40]

  // 3. this method can be used in multiple ways,
  // for now let's get the whole slice
    fmt.Println(s[:]) // [10 20 30 40]

The last part above([:]) has the following syntax slice_name[low:high] and returns a new slice. If we don’t put any values for low and high it will return the completed slice (which clearly means that any or both of these values are optional).

If we enter both low and high values, the expression below will return slice from index 0(low) up to 2; so it excludes the element at index 3 (high)

s := []int{10, 20, 30, 40}
  fmt.Println(s[0:3]) // [10 20 30]