Best practices/syntax sugar on throwing errors with anyhow

I am using the amazing anyhow crate to propogate errors in a rust project I am working on.
Here is a code snippet:

pub fn parse_str(s: &str) -> Result<(String, Vec<String>)> {
	let (key, operations) = s
		.split_once(':')
		.ok_or_else(|| anyhow!("invalid format: expected \"KEY:OP[+OP]*\", found \"{}\"", s))?;

	let (key, operations) = match s.split_once(':') {
		Some(split) => split,
		None => bail!("invalid format: expected \"KEY:OP[+OP]*\", found \"{}\"", s),
	};

Both of the "(key, operation)" code blocks work, my question is whether one of them is more of a best practice. Personally, I think the second snippet is much more explicit and easier to read, I just find the Some(split) => split to be a little unnecessary and wanted to ask if there exists any syntax sugar in Rust to get rid of it or make it shorter somehow.
Thanks for your help!

You can also use the new let-else syntax:

let Some((key, operation)) = s.split_once(':') else { bail!("invalid format: expected \"KEY:OP[+OP]*\", found {:?}", s) };
3 Likes

I personally prefer the match statement.

3 Likes

Thanks, I only knew about if let Some(x) = ... until now, this seems like a pretty clean solution!

Oh, cool to see that landed!

1 Like