mirror of
https://github.com/rust-lang/book.git
synced 2026-09-15 05:29:45 -04:00
Explain that string slice ranges are half-open
The discussion as a whole makes it clear that the ending index is exclusive, but because of the way people new to the language will be reading this, I think it is very important to make this explicit. Some languages include a `[a..b]` syntax that looks very similar to Rust's, but not all of them use the same rules. Someone coming from Ruby, where this notation on a string signifies a closed interval where both endpoints are included may be very confused for a while right here.
This commit is contained in:
@@ -151,10 +151,13 @@ This is similar to taking a reference to the whole `String` but with the extra
|
||||
`[0..5]` bit. Rather than a reference to the entire `String`, it’s a reference
|
||||
to a portion of the `String`.
|
||||
|
||||
We create slices with a range of `[starting_index..ending_index]`, but the
|
||||
slice data structure actually stores the starting position and the length of
|
||||
the slice. So in the case of `let world = &s[6..11];`, `world` would be a slice
|
||||
that contains a pointer to the 6th byte of `s` and a length value of 5.
|
||||
We create slices with a range of `[starting_index..ending_index]`, where
|
||||
`starting_index` is the first position included in the slice and
|
||||
`ending_index` is the one more than the last position included in the slice.
|
||||
Internally, the slice data structure actually stores the starting position and
|
||||
the length of the slice, which corresponds to `starting_index` minus
|
||||
`ending_index`. So in the case of `let world = &s[6..11];`, `world` would be a
|
||||
slice that contains a pointer to the 6th byte of `s` and a length value of 5.
|
||||
|
||||
Figure 4-12 shows this in a diagram.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user