来自fn的Rust返回结果错误

abd*_*doe 3 rust rust-result

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

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

错误信息

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`
Run Code Online (Sandbox Code Playgroud)

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

Ki *_*ang 9

错误信息非常清楚.你的返回类型get_resultResult<String, std::io::Error>,意味着在这种Result::Ok情况下,Ok变体的内部值是类型String,而在这种Result::Err情况下,Err变体的内部值是类型std::io::Error.

您的代码尝试创建Err内部值为type 的变体String,并且编译器正确地抱怨类型不匹配.要创建新的std::io::Error,可以使用该new方法std::io::Error.以下是使用正确类型的代码示例:

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


Mal*_*ice 5

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

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)
    };
}
Run Code Online (Sandbox Code Playgroud)

不过我不建议这样做。