rust match wildcard
Rust Match Wildcard
In Rust, the match expression is used for pattern matching. The wildcard pattern _
can be used to match any value. It is often used as a catch-all case when you don't need to handle a specific value. Here's an example of using the wildcard pattern in a match expression:
fn main() {
let value = 42;
match value {
0 => println!("Zero"),
1 => println!("One"),
_ => println!("Other"), // Wildcard pattern
}
}
In the above code, if the value is 0
, it will print "Zero". If the value is 1
, it will print "One". For any other value, the wildcard pattern _
will match, and it will print "Other".
The wildcard pattern can also be used in combination with other patterns. For example:
fn main() {
let value = Some(42);
match value {
Some(0) => println!("Zero"),
Some(1) => println!("One"),
Some(_) => println!("Other"), // Wildcard pattern
None => println!("None"),
}
}
In this case, if the value is Some(0)
, it will print "Zero". If the value is Some(1)
, it will print "One". If the value is Some
with any other value, the wildcard pattern _
will match, and it will print "Other". If the value is None
, it will print "None".
I hope this helps! Let me know if you have any further questions.