Junior — Middle
Is it possible for a variable len to show a smaller length than the actual size of an array or slice?
sobes.tech AI
Answer from AI
In Go, the variable len for an array or slice always reflects the current length returned by the built-in len() function.
- For an array,
lenis always equal to the size of the array and does not change. - For a slice,
lenshows the number of elements in the slice, which can be less than or equal to the capacity of the slice.
A situation where len is less than the actual size of the array is impossible, as len for an array is fixed and equal to its size.
For a slice, the length can be less than the capacity but not greater than the actual number of elements accessible by index.
Example:
arr := [5]int{1,2,3,4,5}
fmt.Println(len(arr)) // 5
slice := arr[1:3]
fmt.Println(len(slice)) // 2
fmt.Println(cap(slice)) // 4
Here, the length of the slice is 2, although the capacity is 4. But the length cannot be greater than the actual size of the slice.