vendredi 6 décembre 2019

"if" statement gets executed when the condition is "false" in a Rust program, how to understand it?

For the following Rust program:

fn main() {
    let foo = "test".to_string();
    if false {
        let _bar = foo; // value moved to _bar
    }
    println!("{}", foo);
}

I got this error when run it:

error[E0382]: borrow of moved value: `foo`
 --> src\main.rs:6:20
  |
2 |     let foo = "test".to_string();
  |         --- move occurs because `foo` has type `std::string::String`, which does not implement the `Copy` trait
3 |     if false {
4 |         let _bar = foo; // value moved to _bar
  |                    --- value moved here
5 |     }
6 |     println!("{}", foo);
  |                    ^^^ value borrowed here after move

Could anyone help to explain what happens here? It's weird to me that the move happens in a if statement which will never be true. Also I want to know more about this situation, what keywords should I use to search?

Aucun commentaire:

Enregistrer un commentaire