Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to get the length of an array in Golang

Gutha Vamsi Krishna

In this shot, we will learn how to get the length of an array using Golang.

Arrays in Golang are of fixed size, i.e., we need to provide the size of an array while declaring it. We cannot change the size of an array later.

We can calculate the size of an array in Golang using the len() method.

It takes the name of an array as a parameter and returns the size of the array.


package main

//Program execution starts here
func main() {
    //Declare array fruits
    fruits := [4]string{"apple", "orange", "grapes", "guava"}

    //calculate size of the array fruits
    fruitsLength := len(fruits)

    //display the size
    println("Length of an Array is :", fruitsLength)


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 values of datatype string.
  • 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.



View all Courses

Keep Exploring