0
0
Goprogramming~5 mins

Array length in Go

Choose your learning style9 modes available
Introduction
Knowing the length of an array helps you understand how many items it holds so you can work with all of them safely.
When you want to loop through all items in an array.
When you need to check if an array is empty before using it.
When you want to allocate space or resources based on the number of items.
When you want to compare sizes of two arrays.
When you want to avoid errors by not accessing beyond the array's end.
Syntax
Go
package main

import "fmt"

func main() {
    var numbers [5]int
    length := len(numbers)
    fmt.Println("Length of array:", length)
}
Use the built-in len() function to get the length of an array.
The length is fixed for arrays in Go and known at compile time.
Examples
An array with zero length returns 0.
Go
var emptyArray [0]int
fmt.Println(len(emptyArray))
An array with one element returns length 1.
Go
var singleElementArray [1]string
fmt.Println(len(singleElementArray))
An array with three elements returns length 3.
Go
var fruits [3]string = [3]string{"apple", "banana", "cherry"}
fmt.Println(len(fruits))
Sample Program
This program creates an array of 4 colors, prints the array, then prints its length using len().
Go
package main

import "fmt"

func main() {
    var colors [4]string = [4]string{"red", "green", "blue", "yellow"}
    fmt.Println("Array before:", colors)
    length := len(colors)
    fmt.Println("Length of array:", length)
}
OutputSuccess
Important Notes
Time complexity of len() on arrays is O(1) because length is stored with the array.
Space complexity is O(1) since no extra space is used to get length.
Common mistake: Trying to use len() on a nil slice or pointer without initialization causes errors.
Use len() on arrays when you need to know the fixed size; for slices, len() gives the current number of elements.
Summary
Use len() to find how many items are in an array.
Array length is fixed and known at compile time in Go.
Knowing length helps avoid errors when accessing array elements.