How to get the length of an array in Golang

Key takeaways:

  • Understanding how to find the length of an array is crucial in various domains, such as web development, data science, and user interface design.

  • Go arrays are of fixed size and store data of the same type.

  • The len() function is used to calculate the size of an array. It takes the array name as a parameter and returns its length.

  • The len() function can also be used to find the length of sliced arrays, allowing for dynamic array manipulation.

  • The len() function on a two-dimensional array returns the number of rows. To find the number of columns in a specific row, access the row by index and then use len(), like len(myArray[0]).

Understanding how to find the length of an array is a fundamental operation. It is difficult to think of a domain that doesn’t require array length in one of its steps—web developmentdata science, and user interface development; naming just a few wouldn’t be possible without it. Several applications rely on array length:

  • Pagination: Calculates the number of pages needed to display a dataset.

  • Feature selection: Assesses the number of features in datasets.

  • User interface design: Dynamically adjusts the display of items in lists or drop-downs based on the length.

What is an array in Go?

Arrays in Golang are of fixed-size data structure and are used to store data of the same type. For example, a list of peoples’ ages can comprise an array. We need to provide the size of an array while declaring it. We cannot change the size of an array later.

An array representation
An array representation

Go, by Griesemer et al., makes finding the length of an array process straightforward. In Golang, we use the following function to find the array length:

  • The Len() function

Merge sort, invented by John von Neumann, sorts arrays by splitting them into two halves. First, we need the array length to do this correctly. Knowing the length helps us divide the array, recognize when we’ve reached a single element (already sorted), and manage memory effectively when merging. It’s a simple but vital step in the process!

The len() function

In Golang, we can calculate the size of an array using the len() method. This method takes the array’s name as a parameter and returns its size.

len(arrayname)

Let’s see the code example of the len() function to find the array length in Golang.

package main
//Program execution starts here
func main() {
//Declare array fruits
fruits := [4]string{"apple", "orange", "grapes", "guava"}
//calculate size of the array of fruits
fruitsLength := len(fruits)
//display the size
println("Length of an Array is :", fruitsLength)
}

Explanation

In the code snippet above:

  • Line 4: The main() function is the starting point for program execution.
  • Line 6: Declare an array fruits, which stores data type string values.
  • Line 9: Calculate the length of the array fruits using the len() method, where fruits is passed as a parameter.
  • Line 12: Display the length of the array fruits, which is then assigned to the variable fruitsLength.

How to get the length of the sliced array

We can get the length of the sliced array using the len() function. The following code demonstrates the usage of the len() function to get the length of the sliced array.

package main
//Program execution starts here
func main() {
//Declare array fruits
fruits := [5]string{"apple", "orange", "grapes", "guava"}
//Slicing the array fruits
var sliceArray = fruits[:3]
//calculate size of the sliced array fruits
fruitssliceLen := len(sliceArray)
//display the capacity
println("Length of an sliced Array is :", fruitssliceLen)
}

How to use the len() function for two-dimensional arrays

The len() function of a two-dimensional array returns the length of its outer array. It will return the number of rows in the two-dimensional array. If we want to know the length of the inner array, we can access the row using its index and then apply the len() method.

package main
import "fmt"
// Program execution starts here
func main() {
// Declare a 2D array of fruits
fruits := [2][3]string{
{"apple", "orange", "grapes"},
{"guava", "banana", "mango"},
}
//calculate size of the outer array fruits
fruitsouterLength := len(fruits)
// Display the size of the outer array fruits
fmt.Println("length of outer fruits array:", fruitsouterLength)
//calculate size of the inner array fruits
fruitsinnerLength := len(fruits[0])
// Display the size of the inner array fruits
fmt.Println("length of inner fruits array:", fruitsinnerLength)
}

Want to learn Go and unlock its full potential? The Way to Go course is your perfect starting point! This course will teach you Go's core constructs and advanced concepts like error-handling, networking, and templating and help you master efficient programming techniques. With hands-on projects and real-world examples, you’ll gain the skills to build robust, concurrent applications.

Start your journey to mastering Go today!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we determine the length or size of an Array in Java?

Use the Array.length property to determine the length or size of an Array in Java.


How Golang declares array without the length?

In Golang, we can declare array without specifying length in the following way:

array := []int{2, 3, 5, 7, 11, 13}

How Go adds element to an array?

In Golang, we can add element to an array using the append() method:

arr := []int{1, 2, 3}
arrayExtend = append(arr, 4) 

How do we find the length of an array pointer in Golang?

We can find the length of a Go array pointer in the following way:

 arr := [5]int{5, 4, 3, 2, 1}
 ptr := &arr
length := len(*ptr) 

How do we find the length of a string in Golang?

We can find the length of a string in Golang with two methods: len() and RuneCountInString().


Can we change the size of an array after it has been declared?

No, in Go, the size of an array is fixed at the time of declaration and cannot be changed later.


Free Resources