2

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
Derek Mahar
  • 27,608
  • 43
  • 124
  • 174

1 Answers1

1

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.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • Does this also mean that `&v[0..0]` when `v` is empty also does not panic? – Derek Mahar Jul 19 '21 at 22:28
  • 1
    @DerekMahar "Panics if begin or end does not point to the starting byte offset of a character (as defined by is_char_boundary), if begin > end, or if end > len." https://doc.rust-lang.org/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E. So &v[0..0], never panic. – Stargateur Jul 19 '21 at 22:41