I am new to Rust, coming from Go.
I was doing rustlings primitive_types4.rs and slicing does not make sense for me.
let a = [1, 2, 3, 4, 5];
let nice_slice = &a[TODO];
assert_eq!([2, 3, 4], nice_slice);
The starting index makes sense, counting from 0th. Resulting in [1..TODO]
.
..
for me means 'through', confirmed by Bash:
$ echo {1..3}
1 2 3
The Rust Book says:
We create slices using a range within brackets by specifying
[starting_index..ending_index]
.
a[3] == 4
. 4's index is 3. Thus, I'd expect [1..3]
to work, but it actually results in [2, 3]
.
As a second guess, I'd try [1..3]
with the thinking of 'from index 1, result.len() == 3' ('I want n items.'), the result is the same, [2, 3]
.
For me, actual Rust behaviour ([1..4]
) is the weirdest. I could define it as 'start index is start index; end index is result.len() - start_index
, or end_index+1. If I have an output I want in mind, it requires the most thinking of the three.
How does this make sense for practical use? I see myself making off by one by errors with this. Is it heritage from C? Should I be thinking different?