How to Find Length of Array in Go: Simple Guide
In Go, you find the length of an array using the
len() function. Just pass your array variable inside len(), and it returns the number of elements in the array.Syntax
The syntax to find the length of an array in Go is simple:
len(arrayName): Returns the number of elements in the array.
Here, arrayName is your array variable.
go
length := len(arrayName)Example
This example shows how to declare an array and find its length using len(). It prints the length to the console.
go
package main import "fmt" func main() { numbers := [5]int{10, 20, 30, 40, 50} length := len(numbers) fmt.Println("Length of array:", length) }
Output
Length of array: 5
Common Pitfalls
Some common mistakes when finding array length in Go:
- Using
len()on a slice works the same, but slices can change size, unlike arrays. - Trying to get length by accessing an index like
arrayName.lengthdoes not work in Go. - Confusing arrays with slices: arrays have fixed size, slices are more flexible.
go
package main import "fmt" func main() { arr := [3]int{1, 2, 3} // Wrong: fmt.Println(arr.length) // This will cause a compile error fmt.Println(len(arr)) // Correct way }
Output
3
Quick Reference
Remember these points when working with array length in Go:
len(array)returns the number of elements.- Arrays have fixed size; slices can grow or shrink.
- Use
len()for both arrays and slices.
Key Takeaways
Use the built-in len() function to get the length of an array in Go.
len() works for both arrays and slices but remember arrays have fixed size.
Do not try to access length as a property like array.length; it causes errors.
Slices are more flexible than arrays but len() usage is the same.
Always pass the array variable inside len() to get its size.