Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature suggestion: ensure_some!() for unwrapping options #370

Closed
SimonSapin opened this issue May 17, 2024 · 3 comments
Closed

Feature suggestion: ensure_some!() for unwrapping options #370

SimonSapin opened this issue May 17, 2024 · 3 comments

Comments

@SimonSapin
Copy link

I found it it pretty common to want to get at the value inside an Option, or propagate an error if it’s None. For example with Iterator::next, u32::checked_sub, etc. Do you think the macro below would make a good addition to the library?

macro_rules! ensure_some {
    ($option: expr, $($tt:tt)+) => {
        if let Some(value) = $option {
            value
        } else {
            anyhow::bail!($($tt)+)
        }
    };
}
@dtolnay
Copy link
Owner

dtolnay commented May 17, 2024

I would prefer to leave it to downstream crates to define that macro for themself, and not build it into this crate.

@SimonSapin SimonSapin closed this as not planned Won't fix, can't repro, duplicate, stale May 18, 2024
@dtolnay
Copy link
Owner

dtolnay commented May 18, 2024

For static string messages, anyhow::Context is pretty good for the same use case:
let jobs = NonZeroU32::new(args.jobs).context("number of jobs must be non-zero")?;

There is .with_context(|| format!("...", ...))? but it wouldn't really be less verbose than the if let.

@SimonSapin
Copy link
Author

I didn’t realize Context was also implemented for Option, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants