'How can I destructure tuples into typed variables?

I'm trying to decompose a tuple into variables, and then cause an error by having one of the types mentioned incorrectly:

fn main() {
    let tup = (500, 6.4, 1);
    let (x: bool, y: f32, z: i16) = tup;
    println!("{}, {}, {}", x, y, z);
}

My idea was that the compiler would raise an error because x is given as bool but is being matched to 500. Surprisingly, it's the last statement where the compiler complains, saying that x, y, and z were not found in this scope:

I tried it another way:

fn main() {
    let tup = (500, 6.4, 1);
    let mut x: bool = true;
    let mut y: f32 = true;
    let mut z: i16 = true;
    (x, y, z) = tup;
    println!("{}, {}, {}", x, y, z);
}

This time, the compiler does raise the expected error, but it also says that the left-hand side of (x, y, z) = tup; isn't valid. Can someone explain what's happening?



Solution 1:[1]

When doing tuple assignment, you should first specify all your variables, then all the types:

let (x, y, z): (bool, f32, i16) = tup;

gives the error you expect (playground)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jmb