【问题标题】:Rust returns a result error from fn: mismatched typesRust 从 fn 返回结果错误:类型不匹配
【发布时间】:2018-01-16 21:42:42
【问题描述】:

我希望这个函数返回错误结果:

fn get_result() -> Result<String, std::io::Error> {
     // Ok(String::from("foo")) <- works fine
     Result::Err(String::from("foo"))
}

错误信息

error[E0308]: mismatched types
 --> src/main.rs:3:17
  |
3 |     Result::Err(String::from("foo"))
  |                 ^^^^^^^^^^^^^^^^^^^ expected struct `std::io::Error`, found struct `std::string::String`
  |
  = note: expected type `std::io::Error`
             found type `std::string::String`

我很困惑如何在使用预期的结构时打印出错误消息。

【问题讨论】:

  • 您需要澄清这个问题。这里没有任何内容涉及打印。 Result 只是一个普通的数据类型。问题是如何让 Rust 根据get_result 的返回类型打印错误,还是更多关于如何修复类型错误?目前你只是有不匹配的类型,如果你有一个字符串错误,不清楚为什么要使用 std::io::Error 开始。
  • 编译器和代码一目了然。您必须输入std::io::Error,然后输入String。你有什么问题?

标签: rust rust-result


【解决方案1】:

如果我做对了,你可能想做这样的事情......

fn get_result() -> Result<String, String> {
   // Ok(String::from("foo")) <- works fine
   Result::Err(String::from("Error"))
}

fn main(){
    match get_result(){
        Ok(s) => println!("{}",s),
        Err(s) => println!("{}",s)
    };
}

我不建议这样做。

【讨论】:

    【解决方案2】:

    错误信息很清楚。 get_result 的返回类型是 Result&lt;String, std::io::Error&gt;,这意味着在 Result::Ok 情况下,Ok 变体的内部值是 String 类型,而在 Result::Err 情况下,内部值Err 变体的类型为 std::io::Error。

    您的代码试图创建一个内部值为String 类型的Err 变体,编译器理所当然地抱怨类型不匹配。要创建新的std::io::Error,您可以使用new method on std::io::Error。这是使用正确类型的代码示例:

    fn get_result() -> Result<String, std::io::Error> {
        Err(std::io::Error::new(std::io::ErrorKind::Other, "foo"))
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-31
      • 2020-12-30
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多