Why can the assignment operator be chained in Rust?

Viewed 875

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.

2 Answers

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.

Here is one reason I can think of. Having assignment as an expression allows for more streamlined syntax in some cases.

match x {
    Some(b) => a = b,
    None => a = 1,
}

Otherwise, the above would have to be written as:

match x {
    Some(b) => {
        a = b;
    },
    None => {
        a = 1;
    },
}
Related