1

I recently came across this expression in some code written by GUILLAUME ENDIGNOUX, which produces a vector of 10 numbers:

 (10 * i..10 * (i + 1)).collect()

Gives: 420, 421, 422, 423, 424, 425, 426, 427, 428, 429

Here is a working example, where I have replaced the number "10" with "3" to simplify:

fn main() {
    let v = get_data(42);
    assert_eq!(v, [126, 127, 128]);
}

fn get_data(i: usize) -> Vec<usize>{
    (3 * i..3 * (i + 1)).collect() // How does this work?
}

What is going on here?

Changing the first number to for instance 1,like so:

( 1 * i..3 * (i + 1)).collect()

I expected the vecor to contain 1 element, but I got all numbers from 42 to 128 (inclusive). I.e. 86 numbers in total.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197

1 Answers1

6

The .. operator has fairly low precedence meaning that your multiplication applies before it.

So

(1 * i..3 * (i + 1)).collect()

is equivalent to

((1 * i)..(3 * (i + 1)).collect()

with a value 42 for i that gives the range 42..129, matching what you observe.

cafce25
  • 15,907
  • 4
  • 25
  • 31