Am learning go and I think I now understand the array to slice range parameters, but I keep coming back to the same nagging question. Why is the second range parameter the length from the source array? Wouldn’t it of made more sense to have it as the length starting from the first parameter? Or, alternatively, a second offset? As it is, in my head, I have to do an end - 1 calculation, which is a little annoying.
To better explain this, here is some sample code:
package main
import (
"fmt"
)
func main() {
darr := [...]int{10, 20, 30, 40, 50, 60, 70}
dslice := darr[3:5]
fmt.Println(dslice)
}
Result:
[40 50]
From the above dslice assignment, 3 is the third index (starting from zero) and 5 is the length from the source array minus one. If this was a spreadsheet, the cell range would of been written as [3:4].
An analogy. You walk into a room with a window and you want to know the length of that window. The go programmer says, “the first point of the window is 3m from the door and the second point is 5m from the door”. True, but you could of just said “it’s 2m long.”. Alternatively, the spreadsheet analogy would of said “the window occupies the two spaces at 3m and 4m”. In any event, the go way of doing this forces the reader to do a minus calculation.
Hope I’ve explained this okay.