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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…