A question I had about slice indexing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<gerep> andlabs, the element 0 is "g", 1 is "o", etc. When I do [1:4] it will return "g" as the element at position one because it counts the slice starting from zero. If I'm expecting the count to start from 0, the element at position 4 would be "n" and not "a" | |
<gerep> andlabs, and this way, for 4 to be "a", the slice count has to start from 1: position 1 = "g", 2 = "o", etc | |
<andlabs> the element at position 4 starting at 0 is n | |
<gerep> andlabs, yes! | |
<andlabs> ut that 4 is the first element /after the end of the slice/ | |
<andlabs> so you get everything from 1 /up to but not including/ 4 | |
<gerep> andlabs, yes, and why not use [1:3] ? | |
<gerep> andlabs, because the 1 is included but the 4 is not | |
<andlabs> because this type of coordinate specification is easier to reason about | |
<andlabs> how many elements are in the slice? 4-1=3 | |
<andlabs> if it was [1:3] then you'd have to say 3-1+1=3 | |
<andlabs> it also means you can say [1:len(x)] to include everything after the first element | |
<andlabs> and not [1:len(x) - 1] | |
<andlabs> what if len(x) is 0? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
s := [6]string{"G","O","L","A","N","G"} | |
fmt.Println(s[1:4]) // [O L A] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment