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:
- Arrays have a fixed length which is determined at the time of declaration.
- The size is part of the array’s type, so
[3]int
and[4]int
are distinct types. - The length of an array can be determined using the built-in
len
function.
Slices:
- Slices are more dynamic and are built on top of arrays.
- They have both a “length” and a “capacity”:
- Length: The current number of elements in the slice.
- Capacity: The total number of elements the underlying array of the slice can accommodate without allocating a new array.
- You can use the built-in
len
function to get the length of a slice and thecap
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
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.