ideasman42
ideasman42

Reputation: 47978

Assign a single value to multiple variables in one line in Rust?

A common way to assign multiple variables is often expressed in programming languages such as C or Python as:

a = b = c = value;

Is there an equivalent to this in Rust, or do you need to write it out?

a = value;
b = value;
c = value;

Apologies if this is obvious, but all my searches lead to Q&A regarding tuple assignment.

Upvotes: 23

Views: 16052

Answers (5)

DreamConspiracy
DreamConspiracy

Reputation: 393

Actually, you can totally do this!

let a @ b @ c = value;

This uses the @ syntax in patterns, which is used to bind a value to a variable, but keep pattern matching. So this binds value to a (by copy), and then continues to match the pattern b @ c, which binds value to b, and so on.

But please don't. This is confusing and of little to no benefit over writing multiple statements.

Upvotes: 8

Miles
Miles

Reputation: 32468

You cannot chain the result of assignments together. However, you can assign multiple variables with a single statement.

In a let statement, you can bind multiple names by using an irrefutable pattern on the left side of the assignment:

let (a, b) = (1, 2);

(Since Rust 1.59, you can also have multiple values in the left side of any assignment, not just let statements.)

In order to assign the same value to multiple variables without repeating the value, you can use a slice pattern as the left-hand side of the assignment, and an array expression on the right side to repeat the value, if it implements Copy:

let value = 42;
let [a, b, c] = [value; 3]; // or: let [mut a, mut b, mut c] = ...
println!("{} {} {}", a, b, c); // prints: 42 42 42

(Playground)

Upvotes: 21

danfo
danfo

Reputation: 21

Using const generics:

fn main() {
    let [a, b, c] = fill_new_slice(1);
    dbg!(a, b, c);
}

fn fill_new_slice<T: Copy, const N: usize>(value: T) -> [T; N] {
    [value; N]
}
$ cargo run --quiet
[src/main.rs:3] a = 1
[src/main.rs:3] b = 1
[src/main.rs:3] c = 1

Upvotes: 2

Frank Moreno
Frank Moreno

Reputation: 344

In Rust, the expression a = b = c = value; is the same to a = (b = (c = value));

And the (x = ...) returns (). Then, the first expression is an equivalent of the following:

c = value;
b = ();
a = ();

Note that the expression has a semicolon in the end, but if the expression were in the last line as a function's return like this a = b = c = value, the equivalente would be the following:

c = value;
b = ();
a = () // without the semicolon

Upvotes: 0

DK.
DK.

Reputation: 58975

No, there is no equivalent. Yes, you have to write multiple assignments, or write a macro which itself does multiple assignments.

Upvotes: 25

Related Questions