An array is a collection of a numbered sequence of elements. Arrays are one of the most important data structures in most programming languages.

In this brief article, we will learn how to determine the length and capacity of an array in the Go programming language.

Go Len() Function

To determine the length of the array, we can use the len() method. Let us start by creating an array as:

my_array := []string{“a”, “b”, “c”, “d”}

The above snippet creates an array of strings.

To determine the length, we use the len() function as shown:

package main


import “fmt”


func main() {


    my_array := []string{“a”, “b”, “c”, “d”}


    fmt.Println(“Length: “, len(my_array))

}

The above code should return the length of the array as:

$ go run array_length.go


Length:  4

The len() function works on both arrays and slices. Keep in mind that the size of the slice is pre-defined as that of an array.

Array Length & Capacity

An array has a length and capacity. The capacity refers to the total number of items an array can hold, while the length is the number of items it currently holds.

Sometimes, both the length and the capacity are of the same value.

Consider the example below:

package main


import “fmt”


func main() {


    my_array := []string{“a”, “b”, “c”, “d”}


    fmt.Println(“Length: “, len(my_array))


    fmt.Println(“Capacity: “, cap(my_array))

    // append elements


    my_array = append(my_array, “e”)

    fmt.Println(“Length: “, len(my_array))


    fmt.Println(“Capacity: “, cap(my_array))

}

In the example above, we create an array of string types. Before appending a new element, the length and capacity of the array are the same as.

However, once we append a new element, the array’s length grows by 1 while the capacity grows by 3.

The resulting output is as:

$ go run array_length.go


Length:  4


Capacity:  4


Length:  5


Capacity:  8

Conclusion

This guide covered how to determine the length and size of an array in the go programming language.

Happy coding!!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352b419900.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list