为什么我得到“必须使用的未使用结果......结果可能是一个 Err 变体,应该处理"?即使我正在处理它? [英] Why am I getting "unused Result which must be used ... Result may be an Err variant, which should be handled" even though I am handling it?
问题描述
fn main() {
foo().map_err(|err| println!("{:?}", err));
}
fn foo() -> Result<(), std::io::Error> {
Ok(())
}
结果:
warning: unused `std::result::Result` that must be used
--> src/main.rs:2:5
|
2 | foo().map_err(|err| println!("{:?}", err));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_must_use)] on by default
= note: this `Result` may be an `Err` variant, which should be handled
Finished dev [unoptimized + debuginfo] target(s) in 0.58s
Running `target/debug/playground`
推荐答案
您不是在处理结果,而是将结果从一种类型映射到另一种类型.
You're not handling the result, you're mapping the result from one type to another.
foo().map_err(|err| println!("{:?}", err));
该行的作用是调用 foo()
,它返回 Result<(), std::io::Error>
.然后 map_err
使用您的闭包返回的类型(在本例中为 ()
),并修改错误类型并返回 Result<(), ()>;代码>.这是您没有处理的结果.由于您似乎只想忽略此结果,因此最简单的方法可能是调用
ok()
.
What that line does is call foo()
, which returns Result<(), std::io::Error>
. Then map_err
uses the type returned by your closure (in this case, ()
), and modifies the error type and returns Result<(), ()>
. This is the result that you are not handling. Since you seem to want to just ignore this result, the simplest thing to do would probably be to call ok()
.
foo().map_err(|err| println!("{:?}", err)).ok();
ok()
将 Result
转换为 Option
,将错误转换为 None
>,您不会因为忽略它而收到警告.
ok()
converts Result<T,E>
to Option<T>
, converting errors to None
, which you won't get a warning for ignoring.
或者:
match foo() {
Err(e) => println!("{:?}", e),
_ => ()
}
这篇关于为什么我得到“必须使用的未使用结果......结果可能是一个 Err 变体,应该处理"?即使我正在处理它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!