Length and Capacity
Understanding Array Length
In Golang, array length is a fundamental property that defines the number of elements an array can hold. Unlike slices, arrays have a fixed length that cannot be modified after declaration.
Determining Array Length
package main
import "fmt"
func main() {
numbers := [5]int{10, 20, 30, 40, 50}
// Using len() function to get array length
fmt.Println("Array Length:", len(numbers)) // Output: 5
}
Length vs. Capacity
Property |
Array |
Slice |
Length |
Fixed at declaration |
Can be dynamically changed |
Capacity |
Equals declared size |
Can be larger than length |
Modification |
Cannot be resized |
Can be resized |
Length Calculation Visualization
graph TD
A[Array Length] --> B[Number of Elements]
A --> C[Determined at Compile Time]
A --> D[Immutable]
Practical Length Operations
Iterating Through Array Length
package main
import "fmt"
func main() {
fruits := [4]string{"Apple", "Banana", "Cherry", "Date"}
// Iterating using length
for i := 0; i < len(fruits); i++ {
fmt.Printf("Fruit %d: %s\n", i, fruits[i])
}
}
len()
: Returns the number of elements
- Cannot directly modify array length
- Provides compile-time size information
Memory Considerations
graph LR
A[Array Memory] --> B[Fixed Size]
A --> C[Contiguous Memory Allocation]
A --> D[Predictable Memory Usage]
Advanced Length Techniques
Compile-Time Length Checking
func processArray(arr [5]int) {
// This function only accepts arrays with exactly 5 elements
}
LabEx Learning Insight
At LabEx, we emphasize understanding the immutable nature of array length in Golang as a key concept for efficient memory management.
- Fixed length allows compiler optimizations
- Predictable memory allocation
- No runtime overhead for length determination
Complete Example: Length Demonstration
package main
import "fmt"
func main() {
// Different array declarations
numbers := [5]int{1, 2, 3, 4, 5}
mixedArray := [...]int{10, 20, 30}
fmt.Println("Numbers array length:", len(numbers)) // Output: 5
fmt.Println("Mixed array length:", len(mixedArray)) // Output: 3
}
Common Pitfalls
- Assuming array length can be changed
- Not checking array bounds
- Misunderstanding length vs. capacity differences