Rust returns a result error from fn: mismatched types

孤人 提交于 2019-12-05 04:56:00

问题


I want this function to return an error result:

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

Error Message

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`

I'm confused how I can print out an error message when using the expected struct.


回答1:


The error message is quite clear. Your return type for get_result is Result<String, std::io::Error>, meaning that in the Result::Ok case, the inner value of the Ok variant is of type String, whereas in the Result::Err case, the inner value of the Err variant is of type std::io::Error.

Your code attempted to create an Err variant with an inner value of type String, and the compiler rightfully complains about a type mismatch. To create a new std::io::Error, you can use the new method on std::io::Error. Here's an example of your code using the correct types:

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



回答2:


You might want to do something like this, if I get it right...

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)
    };
}

I wouldn't recommend doing this though.



来源:https://stackoverflow.com/questions/45583246/rust-returns-a-result-error-from-fn-mismatched-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!