Rust has a transpose method, sometimes useful, works especially well with anyhow
:
use std::str::FromStr;
use anyhow::Context;
fn add(a: Option<&str>, b: Option<&str>) -> anyhow::Result<f32> {
let a = a.map(f32::from_str).transpose()?.context("not a value")?;
let b = b.map(f32::from_str).transpose()?.context("not a value")?;
Ok(a + b)
}
fn main() {
println!("{:?}", add(Some("12"), Some("1.2")));
println!("{:?}", add(Some("a"), Some("1.2")));
println!("{:?}", add(None, Some("1.2")));
}
output:
Ok(13.2)
Err(invalid float literal)
Err(not a value)
My links
I'm making my perfect todo, note-taking app Heaplist, you can try it here heaplist.app
And I have a twitter @rsk
Top comments (0)