How can I explicitly specify the type in a multiple-assignment statement?

I am new to rust and trying to get to grips with the fundamentals.
I am trying to do a multiple-assignment as follows.

let (a,b:i64,c) = (43,4563459682450968,"Hello World");

Now I deliberately put the 2nd value quite big, and tried to specify the type as i64
But this returns an error. It isn't the same as declaring it separately with i64.

May I know how I can explicitly specify the type in a multiple assignment statement?

You can type the entire tuple, using wildcards where you want to ignore types:

let (a, b, c): (_, i64, _) = (43, 4563459682450968, "Hello World");

In addition you can just directly specify the type of the number (but this only works for numeric literals)

let (a, b, c) = (43, 4563459682450968_i64, "Hello World");
1 Like

Rust does not have multiple assignment as a fundamental feature; it has patterns as a fundamental feature. The syntax of let is (loosely speaking)

let PATTERN : TYPE = EXPRESSION;

What your statement is actually doing is constructing a 3-element tuple, then taking it apart again. So, you need to specify the type of the tuple (which you can do in whole or in part):

let (a, b, c): (_, i64, _) = (43, 4563459682450968, "Hello World");

// or
let (a, b, c): (i32, i64, &str) = (43, 4563459682450968, "Hello World");

The _ stands for an unspecified type (in the same way as if you did not write any type for the let, but just for that part).

1 Like

This worked! Thanks

This also worked. Thanks. The wildcard was a useful tip.

The patterns part is an interesting piece of information. So there is no such thing as multiple-assignment

Well, remember also that let isn't "assignment" at all -- it's creating new bindings.

Rust does have destructuring assignment, as of 1.59. Which is also not just a multiple assignment feature, since it works more generally than that.

For example, you can do

fn get_foo() -> Foo { Foo { x: 2, y: 3.13 } }
struct Foo { x: i32, y: f32 }    
let mut x = 123;
Foo { x, .. } = get_foo();
dbg!(x);

and get

[src/main.rs:6] x = 2

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=605874a4348a6fa3a48e0d00e222d640

But in assignment like this there's no need to specify the type, since the binding already has a type from when it was created.


The strategy isn't exactly patterns, because of where it occurs and how it's parsed, but it basically works like patterns.

2 Likes