Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

rust - Why isn't this rvalue promoted to an lvalue as specified in the reference?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...