How to Get the Length of an Array in Golang

To get the length of an array in Golang, you can use the built-in “len()” function. The len() function returns the length of an array or a slice, which is the number of elements it contains.

Implementation of len() method

package main

import "fmt"

func main() {
  mainArray := [5]int{1, 2, 3, 4, 5}
  count := len(mainArray)
  fmt.Printf("There are %d elements in the array.\n", count)
}

Output

There are 5 elements in the array.

You can also use the len() function to count the elements in the slice.

package main

import "fmt"

func main() {
  mainSlice := []int{1, 2, 3, 4}
  count := len(mainSlice)
  fmt.Printf("There are %d elements in the slice.\n", count)
}

Output

There are 4 elements in the slice

We used the len() function in both examples to get the number of elements in the array or the slice.

Array length and capacity

Arrays:

  1. Arrays have a fixed length which is determined at the time of declaration.
  2. The size is part of the array’s type, so [3]int and [4]int are distinct types.
  3. The length of an array can be determined using the built-in len function.

Slices:

  1. Slices are more dynamic and are built on top of arrays.
  2. They have both a “length” and a “capacity”:
    1. Length: The current number of elements in the slice.
    2. Capacity: The total number of elements the underlying array of the slice can accommodate without allocating a new array.
  3. You can use the built-in len function to get the length of a slice and the cap function to get its capacity.

Here’s an example to illustrate the difference between length and capacity for slices:

package main

import (
  "fmt"
)

func main() {
  // Creating a slice with length of 3 and capacity of 5
  slice := make([]int, 3, 5)
  slice[0] = 1
  slice[1] = 2
  slice[2] = 3

  fmt.Println("Slice:", slice)
  fmt.Println("Length:", len(slice))
  fmt.Println("Capacity:", cap(slice))

  // Appending an element to the slice
  slice = append(slice, 4)

  fmt.Println("\nAfter appending an element:")
  fmt.Println("Slice:", slice)
  fmt.Println("Length:", len(slice))
  fmt.Println("Capacity:", cap(slice))
}

Output

How to Get the Length of an Array in Golang

That’s it.

Leave a Comment