skgbanga
skgbanga

Reputation: 2667

Why do I get "borrow of moved value" in a loop when the value is not initialized?

This code works:

fn main() {
    for _ in 0..10 {
        let mut s: String = String::new();
        s.push_str("hello");
        println!("{}", s);
    }
}

If I remove String::new():

fn main() {
    for _ in 0..10 {
        let mut s: String;
        s.push_str("hello");
        println!("{}", s);
    }
}

I get a compilation error:

error[E0382]: borrow of moved value: `s`
 --> src/main.rs:4:9
  |
3 |         let mut s: String;
  |             ----- move occurs because `s` has type `String`, which does not implement the `Copy` trait
4 |         s.push_str("hello");
  |         ^ value borrowed here after move
5 |         println!("{}", s);
6 |     }
  |     - value moved here, in previous iteration of loop

This is surprising to me since I assumed that String::new() is only there to initialize the variable. I am not able to figure out why previous iteration of the loop invalidates the variable (by moving).

Upvotes: 1

Views: 316

Answers (1)

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13628

This is a compiler bug. The correct error message would be:

error[E0381]: borrow of possibly-uninitialized variable: `s`
 --> src/main.rs:3:5
  |
3 |     s.push_str("hello");
  |     ^ use of possibly-uninitialized `s`

Upvotes: 3

Related Questions