【问题标题】:Why can't I return an explicitly-typed Result enum from a function?为什么我不能从函数返回显式类型的 Result 枚举?
【发布时间】:2018-05-20 15:20:26
【问题描述】:

简单代码如下:

fn main() {
    let R1 = TestResult(10, 20);
    match R1 {
        Ok(value) => println!("{}", value),
        Err(error) => println!("{}", error),
    }
}

fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
    if a1 > a2 {
        //Compile Pass
        //Ok(100)

        //Compile with error why ?
        std::result::Result<i32, std::string::String>::Ok(100)
    } else {
        Err(String::from("Error Happens!"))
    }
}

我得到了错误

error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `,`
  --> src/main.rs:15:32
   |
15 |         std::result::Result<i32, std::string::String>::Ok(100)
   |                                ^ expected one of 8 possible tokens here

error[E0423]: expected value, found enum `std::result::Result`
  --> src/main.rs:15:9
   |
15 |         std::result::Result<i32, std::string::String>::Ok(100)
   |         ^^^^^^^^^^^^^^^^^^^
   |
   = note: did you mean to use one of the following variants?
           - `std::result::Result::Err`
           - `std::result::Result::Ok`

error[E0423]: expected value, found builtin type `i32`
  --> src/main.rs:15:29
   |
15 |         std::result::Result<i32, std::string::String>::Ok(100)
   |                             ^^^ not a value

error[E0308]: mismatched types
  --> src/main.rs:15:9
   |
9  | fn TestResult(a1: i32, a2: i32) -> Result<i32, String> {
   |                                    ------------------- expected `std::result::Result<i32, std::string::String>` because of return type
...
15 |         std::result::Result<i32, std::string::String>::Ok(100)
   |         ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found bool
   |
   = note: expected type `std::result::Result<i32, std::string::String>`
              found type `bool`

我正在使用 Rust 1.26.0。

【问题讨论】:

  • 局部变量的名称和方法和函数的名称应该使用小写。例如let R1 应该是let r1。这不会修复你的编译器错误,但它是更好的 Rust 风格。

标签: enums rust


【解决方案1】:

因为这是语法错误。正确的语法在 enum 变体上使用 turbofish (::&lt;&gt;):

std::result::Result::Ok::<i32, std::string::String>(100)

你也不应该使用显式类型,除非你真的需要它——这不是惯用的。 Rust 变量和函数使用snake_case

fn main() {
    let r1 = test_result(10, 20);
    match r1 {
        Ok(value) => println!("{}", value),
        Err(error) => println!("{}", error),
    }
}

fn test_result(a1: i32, a2: i32) -> Result<i32, String> {
    if a1 > a2 {
        Ok(100)
    } else {
        Err(String::from("Error Happens!"))
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多