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.
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.
Look at it this way: The first index is inclusive, the last exclusive. This is a common convention in many other languages so the creators of Go just went with it. The upside is that you don’t need to switch your mindset going back and forth between, let’s say, Go and Python.
I guess you are right. I just looked up js and rust and they are like you say, but PHP slice does what it says on the tin i.e. if you want two items you put “2”, not “5 - 3”.
The colon makes it look like a spreadsheet range and I’ve thankfully never had to minus one from it.
As it is, in my head, I have to do an end - 1 calculation, which is a little annoying.
What you mention here is one of the oldest, never ending and unresolved discussions in programming. Same as arguing if collections should start with index of 0 or 1.
Its not something exclusive to golang but to all programming in general.
Btw. recreating array_slice from PHP as a custom utility function in golang should be an easy task.