Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

rust - How do you unwrap a Result on Ok or return from the function on Err?

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,
};

Is there a more idiomatic Rust way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a macro:

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);
}

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!");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...