[英]Rust returns a result error from fn: mismatched types
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
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
. get_result
返回类型是Result<String, std::io::Error>
,这意味着在Result::Ok
情况下, Ok
变量的内部值是String
类型,而在Result::Err
情况下, Err
变体的内部值是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. 您的代码尝试创建一个内部值为
String
类型的Err
变体,并且编译器正确地抱怨类型不匹配。 To create a new std::io::Error
, you can use the new
method on std::io::Error
. 要创建新的
std::io::Error
,可以在std::io::Error
上使用new
方法 。 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"))
}
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. 我不建议这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.