Rust safe optional parsing

Parse positive integers without panics using Rust Option values.

Original Pearto instructional example. Test it in your own environment and adapt it to your requirements.

News & updates

No news stories have been linked to this profile.

Search news coverage ↗

Sources & useful links

No publisher or independent source links have been added to this entry.

Suggest a source or correction ↗
fn parse_positive(raw: &str) -> Option<u32> {
    raw.parse::<u32>().ok().filter(|n| *n > 0)
}
fn main() {
    println!("{:?}", parse_positive("42"));
    println!("{:?}", parse_positive("invalid"));
}