Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching in function arguments #3

Open
aeveris opened this issue Apr 18, 2018 · 0 comments
Open

Pattern matching in function arguments #3

aeveris opened this issue Apr 18, 2018 · 0 comments
Labels
information Awesome helpful information about how the language works

Comments

@aeveris
Copy link
Contributor

aeveris commented Apr 18, 2018

In this stream you tried to use pattern matching in function arguments and were really close to figuring out the correct syntax.
So not to leave you with the impression that it can't be done, here's how you'd use pattern matching to destructure a tuple and print its individual values:

fn main() {
    let tup = (42, 24);
    print_tuple(tup);
}

fn print_tuple((x, y): (u32, u32)) {
    println!("x: {} | y: {}", x, y);
}

You use basically exactly the same syntax as if you were to destructure the tuple using a let statement, e.g. let (x, y) = tup; except that the type annotation is mandatory.
Destructuring of more complex values like structs or enums is also possible as shown in the following example:

struct Coords {
    x: i32,
    y: i32,
    z: i32,
}

fn main() {
    let coords = Coords { x: 2, y: 4, z: 8 };
    print_coords(coords);
}

fn print_coords(Coords{ x, y, z }: Coords) {
    println!("x: {} | y: {} | z: {}", x, y, z);
}

Like with let you can only destructure irrefutable patterns, i.e. patterns that will always match the provided values.

@BrooksPatton BrooksPatton added the information Awesome helpful information about how the language works label Apr 18, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
information Awesome helpful information about how the language works
Projects
None yet
Development

No branches or pull requests

2 participants