Strange error information generate with rustc

fn main(){
    let mut pre;
    let mut now=0;
    for i in 1..10 {
        pre=now;
        now=i;// suppose we are calculating something
    }
    drop(pre);
}

which generates an error:

$ rustc --edition 2021 test.rs  -o test
error[E0381]: used binding `pre` is possibly-uninitialized
 --> test.rs:8:10
  |
2 |     let mut pre;
  |         ------- binding declared here but left uninitialized
3 |     let mut now=0;
4 |     for i in 1..10 {
  |              ----- if the `for` loop runs 0 times, `pre` is not initialized
...
8 |     drop(pre);
  |          ^^^ `pre` used here but it is possibly-uninitialized

error: aborting due to previous error

For more information about this error, try `rustc --explain E0381`.

What cause rustc believe that, for i in 0..10 could runs 0 times?

The language doesn't specify how the iterator works for that range. That's handled in the library by impl Iterator for Range, but the compiler would have to use interprocedural analysis to see how many times this particular iterator loops. Locally, it just sees a loop that could break right away if the iterator returns None.

Once you get down to codegen in LLVM, inlining does allow optimizations for specific loop counts, but that's not part of the language semantics.

4 Likes

See this thread about that on URLO:

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.