我希望这个函数返回一个错误结果:
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[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.
推荐答案错误信息很清楚.get_result 的返回类型是 Result,这意味着在 Result::Ok 的情况下,Ok 变体的内部值是 String 类型,而在 Result::Err 情况下, 的内部值Err 变体属于 std::io::Error 类型.
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.
您的代码试图创建一个具有 String 类型内部值的 Err 变体,并且编译器正确地抱怨类型不匹配.要创建新的 std::io::Error,您可以使用 new 在 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")) }更多推荐
Rust 从 fn 返回结果错误:类型不匹配
发布评论