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?

放肆的年华 提交于 2020-12-26 05:56:07

问题


fn main() {
    foo().map_err(|err| println!("{:?}", err));
}

fn foo() -> Result<(), std::io::Error> {
    Ok(())
}

results:

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`

playground link


回答1:


You're not handling the result, you're mapping the result from one type to another.

foo().map_err(|err| println!("{:?}", err));

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() converts Result<T,E> to Option<T>, converting errors to None, which you won't get a warning for ignoring.

Alternatively:

match foo() {
    Err(e) => println!("{:?}", e),
    _ => ()
}


来源:https://stackoverflow.com/questions/53368303/why-am-i-getting-unused-result-which-must-be-used-result-may-be-an-err-vari

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!