Rust 从 fn 返回结果错误:类型不匹配 [英] Rust returns a result error from fn: mismatched types

查看:69
本文介绍了Rust 从 fn 返回结果错误:类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个函数返回一个错误结果:

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,您可以使用 newstd::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 返回结果错误:类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆