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:
The above snippet creates an array of strings.
To determine the length, we use the len() function as shown:
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:
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:
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:
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!!