Search code examples
rustrangebit-shift

What does bitshift do to a range in Rust?


I'm reading code that contains the following (slightly altered) Rust code:

let new_var : Vec<...> = (0..1 << some_number)
                         .into_par_iter()
                         .map(...)
                         .collect();

I recognize that it iterates over a range and constructs elements of a Vec for each number.
But why does it bitshift the 0..1 range? What is the resulting iterator that gets iterated over?


Solution

  • Left shift operator << has higher precedence than range operator(..). So 1 << some_number evaluates first.

    You can also use the HIR(High-Level Intermediate Representation) as an output mode in rust playground to see how rust compiler parse/generate the HIR for the following code:

    fn main() {
        let a = (0..1 << 2).into_par_iter();
    }
    

    HIR

    #[prelude_import]
    use std::prelude::rust_2021::*;
    #[macro_use]
    extern crate std;
    fn main() {
        let a = #[lang = "Range"]{ start: 0,  end: 1 << 2,}.into_par_iter();
        //                                    ^^^^^^^^^^^
    }