Length and Capacity Methods
Understanding len() Function
In Golang, the len()
function is the primary method for determining the size of an array. It returns the number of elements in the array.
Basic Length Retrieval
package main
import "fmt"
func main() {
// Array declaration
numbers := [5]int{10, 20, 30, 40, 50}
// Get array length
arrayLength := len(numbers)
fmt.Println("Array Length:", arrayLength) // Output: 5
}
Length vs Capacity
graph TD
A[Array Size Methods] --> B[len() Function]
A --> C[cap() Function]
B --> D[Returns Number of Elements]
C --> E[Returns Total Allocated Capacity]
Comparison of Length Methods
Method |
Purpose |
Return Value |
Applicable To |
len() |
Element Count |
Number of elements |
Arrays, Slices, Maps |
cap() |
Capacity |
Total allocated capacity |
Slices, Arrays |
Practical Length Checking Examples
Multiple Array Length Scenarios
package main
import "fmt"
func main() {
// Fixed-size array
fruits := [3]string{"apple", "banana", "orange"}
fmt.Println("Fruits Array Length:", len(fruits))
// Zero-length array
emptyArray := [0]int{}
fmt.Println("Empty Array Length:", len(emptyArray))
// Multidimensional array length
matrix := [2][3]int{{1, 2, 3}, {4, 5, 6}}
fmt.Println("Matrix Row Length:", len(matrix))
fmt.Println("Matrix Column Length:", len(matrix[0]))
}
Advanced Length Checking Techniques
Dynamic Length Calculation
func calculateTotalSize(arrays ...[]int) int {
totalSize := 0
for _, arr := range arrays {
totalSize += len(arr)
}
return totalSize
}
func main() {
arr1 := []int{1, 2, 3}
arr2 := []int{4, 5}
totalArraySize := calculateTotalSize(arr1, arr2)
fmt.Println("Total Array Size:", totalArraySize)
}
len()
is a constant-time operation
- Minimal computational overhead
- Efficient for large arrays and slices
Common Pitfalls
- Checking length of
nil
slice/array can cause runtime panic
- Always validate array/slice before length check
LabEx Recommendation
When working with arrays in Go, consistently use len()
for size determination and implement proper error handling to ensure robust code.