Rust 从 fn 返回结果错误:类型不匹配

编程入门 行业动态 更新时间:2024-10-28 18:24:17
本文介绍了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,您可以使用 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 返回结果错误:类型不匹配

本文发布于:2023-10-28 00:30:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不匹配   错误   类型   Rust   fn

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!