The Rust Reference says:
The left operand of an assignment or compound-assignment expression is an lvalue context, as is the single operand of a unary borrow.
[...]
When an rvalue is used in an lvalue context, a temporary un-named lvalue is created and used instead.
This rvalue promotion obviously works with borrowing:
let ref_to_i32 = &27; // a temporary i32 variable with value 27 is created
But it doesn't seem to work in an assignment (although the reference speaks about all lvalue contexts, not just borrowing):
27 = 28; // error[E0070]: invalid left-hand side expression
The error description of E0070 doesn't mention this rvalue promotion. Is this a mistake in the reference or is there indeed some way to trigger rvalue promotion with assignment or compound assignment expressions?
There is a third kind of lvalue context, which the reference describes incorrectly, too. Whenever there is a pattern with a ref
in it, the left value binding to that pattern is an lvalue context. It turns out that promotion works in this case:
let ref x = 3; // works
So apparently, promotion only doesn't work for (compound-)assignments?
The Lvalue refers to a modifiable object in c++ that can be either left or right side of the assignment operator. The Rvalue refers to a value stored at an address in the memory. It can appear only on the right-hand side of the assignment operator.
An lvalue refers to an object that persists beyond a single expression. An rvalue is a temporary value that does not persist beyond the expression that uses it.
“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable.
The reference has been updated since the time this question was posted. Now it says that rvalue to lvalue promotion doesn't happen during assignment, so this was apparently an error in the old reference.
Borrow operators:
If the & or &mut operators are applied to an rvalue, a temporary value is created
This is probably meant to apply to ref
bindings as well, although I don't see it explicitly mentioned.
Assignment:
The left-hand operand must be an lvalue: using an rvalue results in a compiler error, rather than promoting it to a temporary.
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