Rust: Improve readability in default arm of match statement
#TIL in #rustlang we can use any variable name (starting with _) in ignore path of match
Instead of
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
We can write
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ignore_this => {},`
}
Sure, this is a silly example (Original example from the Rust book)
See this commit for real-world usage.
As you can see, I removed the (now defunct) code comment, by using better variable name over just _
If we don’t want to ignore the value (I know this also seems like a made up example, still ..) then
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
unexpected => println!("Got unexpected number : {}", unexpected),
}
No need for _
at the beginning 😄