Assign a single value to multiple variables in one line in Rust?
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)
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.
No, there is no equivalent. Yes, you have to write multiple assignments, or write a macro which itself does multiple assignments.
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