In Rust, why doesn't &v[1..] panic when the size of vector v is one?

Viewed 123

In the gcd example in Programming Rust, 2nd Edition, why doesn't &numbers[1..] cause an out-of-bounds error in the statement

for m in &numbers[1..]

when the size of vector numbers is one? Doesn't numbers[1] address the second element which is one element beyond the end of the vector?

For example, I expected gcd 45 to panic, but instead it reports a greatest common divisor of 45:

ubuntu@development1:~/Documents/projects/rust/programming_in_rust/examples/gcd$ cargo run 45
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/gcd 45`
The greatest common divisor of [45] is 45
1 Answers

Cause the doc say so:

Panics if begin does not point to the starting byte offset of a character (as defined by is_char_boundary), or if begin > len. source

Since len is 1 in your case 1.. doesn't panic and return a empty slice. Equivalent of 1..1 in your case.

Related