Me and my brother have both ran into a situation with match
statements that have resulted in a confusing error message from rustc
that isn't actually idicative of the real problem. For instance, take this tiny program:
fn main() {
match 4 {
4 => "hello",
_ => unreachable!(),
}
}
It reports an error:
--> src/main.rs:4:14
|
2 | / match 4 {
3 | | 4 => "hello",
| | ------- this is found to be of type `&str`
4 | | _ => unreachable!(),
| | ^^^^^^^^^^^^^^ expected `&str`, found `()`
5 | | }
| |_____- `match` arms have incompatible types
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
"What! I know I've done this before", I was thinking. Panics return "never" ( !
), and thus they don't have to have the same type as the other branches. The error didn't make any sense. Then I realized I was missing a semi-colon at the end of the match statement:
fn main() {
match 4 {
4 => "hello",
_ => unreachable!(),
};
}
Now rust is happy. So the actual problem had nothing to do with branch arms, but actually the fact that main
should have "Expected type ()
, but got type &str
".