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
1.2k views
in Technique[技术] by (71.8m points)

rust - Is there a shortcut to unwrap or continue in a loop?

Consider this:

loop {
    let data = match something() {
        Err(err) => {
            warn!("An error: {}; skipped.", err);
            continue;
        },
        Ok(x) => x
    };

    let data2 = match somethingElse() {
        Err(err) => {
            warn!("An error: {}; skipped.", err);
            continue;
        },
        Ok(x) => x
    };

    // and so on
}

If I didn't need to assign the ok-value to data, I'd use if let Err(err) = something(), but is there a shortcut to the code above that'd avoid copy-pasting the Err/Ok branches on this, I think, typical scenario? Something like the if let that would also return the ok-value.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

While I think that E_net4's answer is probably the best one, I'm adding a macro for posterity in case creating a separate function and early-returning with the ? operator is for some reason undesirable.

Here is a simple skip_fail! macro that continues a containing loop when passed an error:

macro_rules! skip_fail {
    ($res:expr) => {
        match $res {
            Ok(val) => val,
            Err(e) => {
                warn!("An error: {}; skipped.", e);
                continue;
            }
        }
    };
}

This macro can be used as let ok_value = skip_fail!(do_something());

Playground link which uses skip_fail to print out numbers divisible by 1, 2, and 3, and print an error when one of the divisions would truncate.

Again, I believe that using ? in a separate function, and returning an Ok(end_result) if nothing fails, is probably the most idiomatic solution, so if you can use that answer you probably should.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...