On my first day of fiddling with Rust, I tried to execute an empty expression statement. The compiler threw a "value borrowed here after move" error when I tried printing the variable used inside the empty expression statement.
Here is the sample code:
fn main() {
let tstr = String::from("test"); // "move occurs because `tstr` has type `String`, which does not implement the `Copy` trait"
tstr; // causes move? <- "value moved here"
println!("{}",tstr); // "value borrowed here after move"
}
Does the empty expression call some hidden trait of the String method which takes ownership of the object? Or is something else at play here?
Rust is generally considered to be an "expression oriented" language. Broadly speaking, this means that most language constructs are expressions. Expressions are things that evaluate to values, and critically, do so independent of the context that they appear in.
A concrete consequence of this is that whether you write
let foo = <expression>;
or
<expression>;
doesn't affect1 how Rust evaluates <expression>. In particular, it doesn't change whether evaluating <expression> causes a value to be moved.
Since evaluating the right-hand side of
let new_tstr = tstr;
clearly involves moving tstr, so to does evaluating
tstr;
1 At the language level. Rust may of course compile these statements differently so long as the observable behavior remains the same. See "as-if rule."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With