你如何在 Ok 上解包 Result 或从 Err 上的函数返回? [英] How do you unwrap a Result on Ok or return from the function on Err?
本文介绍了你如何在 Ok 上解包 Result 或从 Err 上的函数返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数调用另一个返回 Result
的函数.我需要检查 Result
是 Ok
还是 Err
,如果它是 Err
,我需要 return
从我的函数中提早开始.这就是我现在正在做的:
I have a function that calls another function which returns a Result
. I need to check if the Result
is Ok
or Err
and if it is an Err
, I need to return
early from my function. This is what I'm doing now:
match callable(&mut param) {
Ok(_v) => (),
Err(_e) => return,
};
有没有更惯用的 Rust 方法来做到这一点?
Is there a more idiomatic Rust way to do this?
推荐答案
您可以创建一个宏:
macro_rules! unwrap_or_return {
( $e:expr ) => {
match $e {
Ok(x) => x,
Err(_) => return,
}
}
}
fn callable(param: &mut i32) -> Result<i32, ()> {
Ok(*param)
}
fn main() {
let mut param = 0;
let res = unwrap_or_return!(callable(&mut param));
println!("{:?}", res);
}
请注意,我不建议丢弃错误.Rust 的错误处理非常符合人体工程学,所以我会返回错误,即使只是记录它:
Note that I wouldn't recommend discarding the errors. Rust's error handling is pretty ergonomic, so I would return the error, even if it is only to log it:
fn callable(param: &mut i32) -> Result<i32, ()> {
Ok(*param)
}
fn run() -> Result<(), ()> {
let mut param = 0;
let res = callable(&mut param)?;
println!("{:?}", res);
Ok(())
}
fn main() {
if let Err(()) = run() {
println!("Oops, something went wrong!");
}
}
这篇关于你如何在 Ok 上解包 Result 或从 Err 上的函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文