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

Categories

Rust has several operators that cannot be chained (==, < for example).

But the assignment operator = can be chained.

a = b = 10;

In this case, 10 is assigned to b, and unit () is assigned to a.

Is there any reason why Rust allows us to chain = like this?

I created Clippy issue 6576 about this.

question from:https://stackoverflow.com/questions/65661530/why-can-the-assignment-operator-be-chained-in-rust

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

1 Answer

Almost everything in Rust is an expression and not a statement. The major difference between statements and expressions is that expressions return a value after they execute.

This too holds for assignment operations, which are treated as expressions in Rust. The assignment expression has the return value (), also called unit value. What effect does that have on your program?

This means that your assignment

a = b = 10

is parsed as

a = (b = 10)

Note that the return value of b = 10 is () (since it is an expression), and thus this return value gets assigned to a.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...