Storing a matched value and comparing it to a pattern

Normally, we either use a variable name to match part of a data value, or we use a structural pattern to check that it's the right "shape" and use variable names inside that structural pattern to match and extract the parts of it we're interested in.

We can do both at the same time, though, by using the @ symbol:

if let (1, x @ (_, _), _) = (1, (2, 3), (4, 5, 6)) {
println!("matched x to {:?}", x);
}

So, here we have a pattern that matches a 3-tuple that has 1 as its first item, a 2-tuple as its second item, and anything as its third item, and stores the second item (which it has confirmed is a 2-tuple) in a variable called x. The variable name to store into came before the @, and the pattern to check the match against came after.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.3.167