Number Parsing in Rust

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Rust.

// The standard library provides number parsing functionality
use std::str::FromStr;

fn main() {
    // With parse(), we can convert a string to a f64
    let f: f64 = "1.234".parse().unwrap();
    println!("{}", f);

    // For parsing integers, we can use from_str()
    let i: i64 = i64::from_str("123").unwrap();
    println!("{}", i);

    // Rust can recognize hex-formatted numbers
    let d: i64 = i64::from_str_radix("0x1c8", 16).unwrap();
    println!("{}", d);

    // Parsing unsigned integers
    let u: u64 = u64::from_str("789").unwrap();
    println!("{}", u);

    // Rust doesn't have a direct equivalent to Atoi,
    // but we can use parse() for basic base-10 int parsing
    let k: i32 = "135".parse().unwrap();
    println!("{}", k);

    // Parse functions return a Result, which we can use to handle errors
    let result = "wat".parse::<i32>();
    match result {
        Ok(n) => println!("Successfully parsed: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

To run the program:

$ cargo run
1.234
123
456
789
135
Error: invalid digit found in string

In Rust, number parsing is handled through the FromStr trait and the parse() method, which are part of the standard library. The parse() method returns a Result, allowing for error handling.

For parsing integers with different bases, Rust provides methods like from_str_radix().

Rust’s strong type system and Result type provide a safe way to handle parsing errors, making it less likely to encounter runtime errors due to invalid input.

Next, we’ll look at another common parsing task: URLs.