Introduction
Knowing the length of an array helps you understand how many items it holds so you can work with all of them safely.
package main import "fmt" func main() { var numbers [5]int length := len(numbers) fmt.Println("Length of array:", length) }
var emptyArray [0]int fmt.Println(len(emptyArray))
var singleElementArray [1]string
fmt.Println(len(singleElementArray))var fruits [3]string = [3]string{"apple", "banana", "cherry"} fmt.Println(len(fruits))
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) }
len() function return when used with an array in Go?len() function returns the count of elements in arrays, slices, maps, and strings.len() returns the fixed number of elements it holds.arr in Go?len() is used to get the length of arrays and slices.len(arr) is valid syntax; others are invalid or do not exist in Go.package main
import "fmt"
func main() {
arr := [4]int{10, 20, 30, 40}
fmt.Println(len(arr))
}arr is declared with 4 elements: 10, 20, 30, 40.len() function returns the number of elements, which is 4.package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
fmt.Println(len(arr))
fmt.Println(arr[3])
}arr has length 3, so valid indices are 0, 1, and 2.arr[3] is out of range and causes a runtime panic.arr1 := [5]int{1, 2, 3, 4, 5}
arr2 := [3]int{10, 20, 30}
Which expression correctly checks if arr2 has fewer elements than arr1?arr1 has length 5, arr2 has length 3.len() to get lengths. To check if arr2 is smaller, compare len(arr2) < len(arr1).Pass the test and this pattern moves unknown