Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 503
ideasman42 Avatar asked Aug 07 '16 04:08

ideasman42


People also ask

How can you assign the same value to multiple variables in one line?

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.

Can I assign 2 variables at once?

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.

How do you declare multiple variables in rust?

To declare more than one variable of the same or different types, use a comma-separated list.

Can we assign multiple values to multiple variables at a time?

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.


1 Answers

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)

like image 162
Miles Avatar answered Sep 20 '22 06:09

Miles