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.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.
To declare more than one variable of the same or different types, use a comma-separated list.
We can assign values to multiple variables at once in a single statement in Swift. We need to wrap the variables inside a bracket and assign the values using the equal sign = . The values are also wrapped inside a bracket.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With