【发布时间】:2018-12-05 13:52:45
【问题描述】:
为什么下面的代码在编译时会报错?
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
Ok(n + 1)
}
以下是错误:
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>`
以下两个版本编译没有问题。
-
用
else声明:fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { Err("error") } else { Ok(n + 1) } } -
用
return声明:fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { return Err("error"); } Ok(n + 1) }
我正在使用 Rust 1.27.0。
【问题讨论】:
-
我相信Why does an if without an else always result in () as the value?和Why does the compiler assume that the value of if let should be
()?和return a value from within an if statement in a match statement的答案已经回答了您的问题。如果您不同意,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
标签: if-statement rust return