Golang Array Length

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.

Example

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.

To count the elements in the slice, you can also use the len() function.

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

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

That’s it.

Leave a Comment