GoLang Array len()
In this tutorial, we will learn how to find the length of the given array using in-built method along with working examples of it.
In the Go language, len() is used to return the length of the array. It takes array name as a parameter and return the total number of elements present in the given array.
Array len()
Syntax:
len(array_name)
It accepts array_name as the parameter.
Example 1:
Let us create an array with integer type that holds 5 values and return the length.
package main
import ("fmt")
func main() {
// Decalre an array that hold 5 integers
first := [5]int{34,56,43,22,21}
fmt.Println("Actual Array: ",first)
// Return the length
fmt.Println("Length: ",len(first))
}
Output:
Actual Array: [34 56 43 22 21]
Length: 5
Explanation for the above output:
The length is 5, because there are totally 5 elements in the array.
Example 2:
Let us create an array of with integer type that holds 2 integers and return length.
package main
import ("fmt")
func main() {
// Decalre an array that hold integers of length-5
first := [5]int{1:34,4:56}
fmt.Println("Actual Array: ",first)
// Return the length
fmt.Println("Length: ",len(first))
}
Output:
Actual Array: [0 34 0 0 56]
Length: 5
Explanation for the above output:
As the last element index is 4. The length will be equal to the index+1 of the last element.
Example 3:
Let us create an array with string type that holds 2 strings and return length.
package main
import ("fmt")
func main() {
// Decalre an array that hold strings
first := []string{1:"Hello",2:"gkindex"}
fmt.Println("Actual Array: ",first)
// Return the length
fmt.Println("Length: ",len(first))
}
Output:
Actual Array: [ Hello gkindex]
Length: 3
As the last element index is 2. The length will be equal to the index+1 of the last element.
Conclusion:
Now we know how to return total number of elements in a Golang Array using len() function and understood the implementation with working examples.