Rust has a construct called match
which looks very similar to switch
in other languages. However I observed a very peculiar behavior of match
.
let some_u32_value = 3;
match some_u32_value {
_ => (),
3 => println!("three"),
}
match
respects the order in which the cases/patterns are mentioned. Why does it not report an error if the default (_
) case is at the top? It does give a warning though:
warning: unreachable pattern
--> src/main.rs:5:9
|
5 | 3 => println!("three"),
| ^
|
= note: #[warn(unreachable_patterns)] on by default
A similar construct in Java, the switch, does not preserve any order, so having a default
prior to other cases is not an error (ignoring the fall through behavior).
int x = 0;
switch (x) {
default:
System.out.println("default");
break;
case 0:
System.out.println("Zero");
}
Is there some purpose for doing this explicitly?