我希望这个函数返回一个错误结果:
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`
我很困惑如何在使用预期的结构时打印出错误消息。
错误信息非常清楚。您的返回类型为get_result
is Result<String, std::io::Error>
,这意味着在Result::Ok
情况下,其内在价值Ok
变体是类型String
,而在Result::Err
情况下,其内在价值Err
变体是类型std::io::Error
.
您的代码尝试创建一个Err
具有 type 内部值的变体String
,编译器正确地抱怨类型不匹配。创建一个新的std::io::Error
,您可以使用new方法上std::io::Error https://doc.rust-lang.org/std/io/struct.Error.html#method.new。以下是使用正确类型的代码示例:
fn get_result() -> Result<String, std::io::Error> {
Err(std::io::Error::new(std::io::ErrorKind::Other, "foo"))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)