Hello. I'm new to Rust (but not programming), so I am really curious to know the explanation of very unexpected behaviour of compiler with triple return:
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6901de626d769b2fb19ecb1fcb947588
fn main() {
fn hydrate() -> Result<(), String> {
if 1 == 2 {
Ok(())
} else {
Err("error".to_string())
}
Ok(())
}
}
I get these errors:
error[E0308]: mismatched types
--> src/main.rs:4:4
|
3 | / if 1 == 2 {
4 | | Ok(())
| | ^^^^^^ expected `()`, found `Result<(), _>`
5 | | } else {
6 | | Err("error".to_string())
7 | | }
| |_________- expected this to be `()`
|
= note: expected unit type `()`
found enum `Result<(), _>`
help: you might have meant to return this value
|
4 | return Ok(());
| ++++++ +
error[E0308]: mismatched types
--> src/main.rs:6:4
|
3 | / if 1 == 2 {
4 | | Ok(())
5 | | } else {
6 | | Err("error".to_string())
| | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `Result<_, String>`
7 | | }
| |_________- expected this to be `()`
|
= note: expected unit type `()`
found enum `Result<_, String>`
The error disappears when:
- Removing the last Ok(())
- Adding "return" in if branches
Why? LOL
- Why
return
fixes it? I don't havelet
with if, so it returns it anyway - Why the compiler says like that? Who expects
()
? The function expects Result<(), String>
And did anyone report it as a confusing error? I saw their fixing these types of errors according to their roadmap.