【问题标题】:Result and if/else/return statements E0308 error [duplicate]结果和 if/else/return 语句 E0308 错误 [重复]
【发布时间】: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>`

以下两个版本编译没有问题。

  1. else声明:

    fn test(n: i32) -> Result<i32, &'static str> {
        if n == 0 {
            Err("error")
        }
        else {
            Ok(n + 1)
        }
    }
    
  2. return声明:

    fn test(n: i32) -> Result<i32, &'static str> {
        if n == 0 {
            return Err("error");
        }
        Ok(n + 1)
    }
    

我正在使用 Rust 1.27.0。

【问题讨论】:

标签: if-statement rust return


【解决方案1】:

想象一下这个简化的代码:

fn test() -> i32{
    { 1 }
    2
}

这会失败并出现以下错误:

error[E0308]: mismatched types
 --> src/main.rs:2:11
  |
2 |         { 1 }
  |           ^ expected (), found integral variable
  |
  = note: expected type `()`
             found type `{integer}`

这是因为在 Rust 中,完整的语句必须具有 () 类型。如果要忽略某个值,只需添加一个; 即可将一个值转换为语句,并将类型更改为() 丢弃该值。

这段代码编译:

fn test() -> i32{
    { 1; }
    2
}

您的示例类似,但if 使事情变得更有趣。如果你写:

fn test(c: bool) -> i32{
    if c { 1 }
    2
}

它会像以前一样失败,因为第一条语句的类型不同于()。添加; 即可解决问题:

fn test(c: bool) -> i32{
    if c { 1; }
    2
}

else 也可以编译,因为函数中只有一条语句,并且它的类型与函数的返回类型匹配:

fn test(c: bool) -> i32{
    if c { 1 }
    else { 2 }
}

请注意,两个分支必须具有相同的类型,并且两者都不能有;

添加return 也可以,因为根据定义,return 语句具有(),因此其中任何一个都可以编译:

fn test1(c: bool) -> i32{
    if c { return 1; }
    2
}
fn test2(c: bool) -> i32{
    if c { return 1 }
    2
}
fn test3(c: bool) -> i32{
    if c { return 1; }
    else { 2 }
}
fn test4(c: bool) -> i32{
    if c { return 1; }
    else { return 2; }
}

注意; 在这些return 语句中实际上是可选的,因为它已经是() 类型。

【讨论】:

    猜你喜欢
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2017-11-21
    • 2018-01-16
    • 1970-01-01
    • 2016-11-25
    相关资源
    最近更新 更多