Irrefutable patterns
Irrefutable patterns work just like you'd expect from a variable declaration, but they not only allow single variables, but deconstruction from composite structures, too.
// Definition for below struct MyStruct { some_field: usize, another_field: usize } fn example() { // Simple variable let fun = 69; println!("{}", fun); println!(); // Tuple let tuple = (42, 69); let (first_element, second_element) = tuple; println!("{}", first_element); println!("{}", second_element); println!(); let demo_value = MyStruct { some_field: 42, another_field: 69 }; // Deconstructing a struct let MyStruct { some_field: into_variable, another_field: into_another_variable } = demo_value; println!("{}", into_variable); println!("{}", into_another_variable); } fn main() { example(); }
Now that is pretty convenient already, but this would force you to define a variable for each element inside the structure you want to deconstruct. Luckily, Rust patterns have several ways to make it more convenient if you don't need all those values.
// Definition for below struct MyStruct { some_field: usize, other_field: usize, another_field: usize } fn example() { // Tuple not capturing the middle element let (answer, _, leet) = (42, 69, 1337); println!("{}", answer); println!("{}", leet); println!(); let demo_value = MyStruct { some_field: 42, other_field: 69, another_field: 1337 }; // Struct not capturing one field and using shorthand on another let MyStruct { some_field: struct_answer, other_field, // capture into variable of the same name another_field: _ // do not capture this } = demo_value; println!("{}", struct_answer); println!("{}", other_field); println!(); // Struct only capturing a part of the fields let MyStruct { another_field, .. // don't capture other fields } = demo_value; println!("{}", another_field); } fn main() { example(); }
One question you might ask yourself is "So okay, these are patterns, but why are they called irrefutable? This means there also must be refutable ones, right?". And you are correct, there are refutable patterns!