Am studying go and I believe I now perceive the array to slice vary parameters, however I preserve coming again to the identical nagging query. Why is the second vary parameter the size from the supply array? Wouldn’t it of made extra sense to have it because the size ranging from the primary parameter? Or, alternatively, a second offset? As it’s, in my head, I’ve to do an finish – 1 calculation, which is just a little annoying.
To raised clarify this, right here is a few pattern code:
package deal most important
import (
"fmt"
)
func most important() {
darr := [...]int{10, 20, 30, 40, 50, 60, 70}
dslice := darr[3:5]
fmt.Println(dslice)
}
Outcome:
[40 50]
From the above dslice project, 3 is the third index (ranging from zero) and 5 is the size from the supply array minus one. If this was a spreadsheet, the cell vary would of been written as [3:4].
An analogy. You stroll right into a room with a window and also you need to know the size of that window. The go programmer says, “the primary level of the window is 3m from the door and the second level is 5m from the door”. True, however you could possibly of simply mentioned “it’s 2m lengthy.”. Alternatively, the spreadsheet analogy would of mentioned “the window occupies the 2 areas at 3m and 4m”. In any occasion, the go method of doing this forces the reader to do a minus calculation.
Hope I’ve defined this okay.
Take a look at it this manner: The primary index is inclusive, the final unique. This can be a frequent conference in lots of different languages so the creators of Go simply went with it. The upside is that you just don’t want to modify your mindset going forwards and backwards between, let’s say, Go and Python.
2 Likes
I suppose you’re proper. I simply appeared up js and rust and they’re such as you say, however PHP slice does what it says on the tin i.e. if you need two gadgets you place “2”, not “5 – 3”.
The colon makes it seem like a spreadsheet vary and I’ve fortunately by no means needed to minus one from it.
As it’s, in my head, I’ve to do an finish – 1 calculation, which is just a little annoying.
What you point out right here is without doubt one of the oldest, by no means ending and unresolved discussions in programming. Identical as arguing if collections ought to begin with index of 0 or 1.
Its not one thing unique to golang however to all programming usually.
Btw. recreating array_slice from PHP as a customized utility perform in golang needs to be a simple process.
1 Like