Find the Length of an Array

You can find the length of an array, or to be correct a slice or map, in Go by using the standard library function len(). We use the term array loosely here, as a general variable holding multiple things. Maps tend to have defined keys, whereas slices don’t (more info on the difference here).

We have shown both as examples below, how to get the length of a slice and how to get the length of a map. In Golang, the method is the same for both.

Length of a Slice

We define the entire slice in one go, but you can also use append() to add to the slice. We create a slice of three item then print out the length.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func main() {

	myList := []string{
		"item1",
		"item2",
		"item3",
	}

	lengthOfVar := len(myList)

	fmt.Printf("Num of Items: %d\n", lengthOfVar)

	// Num of Items: 3
}

Length of Map

A map holds a key/value pair and our example below uses a string for both the key and value. We create three items on the map, then print out the length.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func main() {

	myList := make(map[string]string)

	myList["question1"] = "answer1"
	myList["question2"] = "answer2"
	myList["question3"] = "answer3"

	lengthOfVar := len(myList)

	fmt.Printf("Num of Items: %d\n", lengthOfVar)

	// Num of Items: 3
}

golang length of array