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);
|> ^
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.
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.
To declare more than one variable of the same or different types, use a comma-separated list.
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.
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.
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