DEV Community

Roman
Roman

Posted on

Rust transpose method

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")));
}
Enter fullscreen mode Exit fullscreen mode

output:

Ok(13.2)
Err(invalid float literal)
Err(not a value)
Enter fullscreen mode Exit fullscreen mode

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)

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Explore this compelling article, highly praised by the collaborative DEV Community. All developers, whether just starting out or already experienced, are invited to share insights and grow our collective expertise.

A quick “thank you” can lift someone’s spirits—drop your kudos in the comments!

On DEV, sharing experiences sparks innovation and strengthens our connections. If this post resonated with you, a brief note of appreciation goes a long way.

Get Started