Why does the following code raise an error when compiled?
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
Ok(n + 1)
}
Following is the error:
error[E0308]: mismatched types
--> src/main.rs:41:9
|
41 | Err("error")
| ^^^^^^^^^^^^- help: try adding a semicolon: `;`
| |
| expected (), found enum `std::result::Result`
|
= note: expected type `()`
found type `std::result::Result<_, &str>`
The following two versions compile without any problem.
With
else
statement:fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { Err("error") } else { Ok(n + 1) } }
With
return
statement:fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { return Err("error"); } Ok(n + 1) }
I'm using Rust 1.27.0.