How to get the number of elements in an array or the length of the array in Go or Golang?

Published September 3, 2022

To get the number of elements in an array or the length of the array, you can use the len() built-in function and then pass the array variable or the array itself to the function in Go or Golang. The function returns the number of elements in the array.

TL;DR

package main

import "fmt"

func main(){
    // a simple array
    name := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // get the length of the array
    // using the `len()` function and pass the
    // `name` variable as an argument to it
    nameLength := len(name)

    // log the value of `nameLength` variable
    fmt.Println(nameLength) // 3 ✅
}

The length in the array refers to the number of elements currently present inside the array. The length of an array is not to be confused with the capacity of an array. Capacity refers to the total number of elements the array can hold.

For example, let's say we have an array called name with string type values of John Doe, Lily Roy, and Roy Daniels like this,

package main

func main(){
    // a simple array
    name := []string{"John Doe", "Lily Roy", "Roy Daniels"}
}

Now to get the length of the name array we can use the len() function and then pass the name variable as an argument to the function. Let's also make a new variable to hold the value returned from the function.

It can be done like this,

package main

func main(){
    // a simple array
    name := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // get the length of the array
    // using the `len()` function and pass the
    // `name` variable as an argument to it
    nameLength := len(name)
}

Finally, let's log the value of the nameLength variable to the console to see the length of the array.

It can be done like this,

package main

import "fmt"

func main(){
    // a simple array
    name := []string{"John Doe", "Lily Roy", "Roy Daniels"}

    // get the length of the array
    // using the `len()` function and pass the
    // `name` variable as an argument to it
    nameLength := len(name)

    // log the value of `nameLength` variable
    fmt.Println(nameLength) // 3 ✅
}

As you can see that the value of 3 is logged which proves that the name array contains 3 elements.

We have successfully got the number of elements in the array. Yay 🥳!

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter