Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare multiple mutable variables at the same time?

Tags:

rust

I can declare multiple constants like this:

let (a, b, c) = (1, 0.0, 3);

But why can't I do this with mutable variables?

let mut (a, b, c) = (1, 0.0, 3); throws a compile error:

error: expected identifier, found `(`
 --> <anon>:2:13
2 |>     let mut (a, b, c) = (1, 0.0, 3);
  |>             ^
like image 665
KDN Avatar asked Jun 27 '16 03:06

KDN


People also ask

Can you initialize multiple variables at once?

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.

How do you declare multiple variables?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

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.

How do you declare multiple variables in Python?

Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.


1 Answers

The proper syntax is

let (mut a, mut b, mut c) = (1, 0.0, 3);

Mutability is a property of the binding, and a, b, and c are all different bindings, each bound to a specific element of the tuple after the pattern has been matched. Thus they can be individually made mutable.

If you wanted to specify the type, you could do that too:

let (mut a, mut b, mut c): (u8, f32, i32) = (1, 0.0, 3); 

For numeric literals, you could also use the suffix form:

let (mut a, mut b, mut c) = (1u8, 0.0f32, 3i32);

Of course, there's no reason to do this for the example code; it's much simpler to just have 3 separate statements.

declare multiple constants

These aren't constants, they are just immutable variables. A const is a different concept.

like image 122
Shepmaster Avatar answered Sep 19 '22 18:09

Shepmaster