Feature suggestion: ensure_some!() for unwrapping options
Closed this issue · 3 comments
SimonSapin commented
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 commented
I would prefer to leave it to downstream crates to define that macro for themself, and not build it into this crate.
dtolnay commented
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 commented
I didn’t realize Context
was also implemented for Option
, thanks