How to find GoLang Array Length

Arrays are one of the most important data structures in programming. In this post, we are going to see how to find the length of an array in GoLang.

GoLang Array Length using len() function

GoLang len() function is the simplest way to find the length of an array in Go. Here it is in action.

a := []int{1, 2, 3, 4}
fmt.Println(len(a))     // 4

It works on both slices as well as an array. But for slices, the size is not predefined. The size of an array is predefined.

So, it is the most effective over slices than to arrays.

Array length and capacity

The length and capacity are not the same even though in some cases it might seem like that. The capacity is how many items it can hold and length is how many items it is holding. They both are very different.

package main

import (
	"fmt"
)

func main() {
	a := []int{1, 2, 3, 4}
	fmt.Println(len(a))        // 4
	fmt.Println(cap(a))        // 4
	
	a = append(a, 12)
	
	fmt.Println(len(a))        // 5
	fmt.Println(cap(a))        // 8
}

Adding one item suddenly increases the capacity of the array. However, the length of the array is increased by 1.