How to get the size of an array or a slice in Golang?


In case we want to get the size of an array or a slice, we can make use of the built-in len() function that Go provides us with.

Example 1

Let's first explore how to use the len function with an array. Consider the code shown below.

package main

import (
   "fmt"
)

func main() {
   fmt.Println("Inside the main function")

   arr := [3]int{1,2,3}

   fmt.Println("The length of the array is:", len(arr))
}

In the above code, we are using the len function on the array defined as arr.

Output

If we run the command go run main.go on the above code, then we will get the following output.

Inside the main function
The length of the array is: 3

How to get the capacity of a slice?

Now that we know how the len function works in case of an array, let's explore the case where we will use the same function along with the cap function as well.

The cap() function is used to get the capacity of a slice. There's a very noticeable difference between the length of the array and the capacity of the array.

The length of a slice is basically the number of elements that are present in the array. The capacity, on the other hand, is the number of elements in the underlying array, where we count from the first element in the slice.

Example 2

Now, let's consider an example, where we will make use of the len() and the cap() function with a slice.

Consider the code shown below.

package main

import (
   "fmt"
)

func main() {
   sl := []int{2, 3, 5, 7, 10, 15}
   check(sl)

   sl = sl[2:]
   check(sl)

   sl = sl[:0]
   check(sl)
}

func check(sl []int) {
   fmt.Printf("len=%d cap=%d %v\n", len(sl), cap(sl), sl)
}

In the above code, we have used the len and cap functions on the slice defined as sl.

Output

If we run the command go run main.go on the above code, then we will get the following output.

len=6 cap=6 [2 3 5 7 10 15]
len=4 cap=4 [5 7 10 15]
len=0 cap=4 []

Updated on: 01-Nov-2021

679 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements