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.
The error message is quite clear. Your return type for
get_result
isResult<String, std::io::Error>
, meaning that in theResult::Ok
case, the inner value of theOk
variant is of typeString
, whereas in theResult::Err
case, the inner value of theErr
variant is of typestd::io::Error
.Your code attempted to create an
Err
variant with an inner value of typeString
, and the compiler rightfully complains about a type mismatch. To create a newstd::io::Error
, you can use thenew
method onstd::io::Error
. Here's an example of your code using the correct types:You might want to do something like this, if I get it right...
I wouldn't recommend doing this though.