Rust

Parse Strings to Typed Values

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`str::parse::<T>()` works for every type that implements `FromStr` — every numeric type, `bool`, `IpAddr`, `Uuid` (with the crate), etc. Returns `Result` so you can chain with `?`.
Rust
Raw
use std::net::IpAddr;
use std::num::ParseIntError;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Basic
    let n: i32 = "42".parse()?;
    println!("{n}");

    // Typed via turbofish when inference fails
    let pi = "3.14".parse::<f64>()?;
    println!("{pi}");

    // Booleans
    let b: bool = "true".parse()?;
    println!("{b}");

    // IPs (stdlib)
    let ip: IpAddr = "192.168.1.1".parse()?;
    println!("{ip}");

    // Default on parse failure
    let bad: i32 = "xyz".parse().unwrap_or(-1);
    println!("{bad}");                                // -1

    // Result chain — only Ok if every parse succeeded
    let nums: Result<Vec<i32>, ParseIntError> =
        "1 2 3 4 5".split_whitespace().map(str::parse).collect();
    println!("{:?}", nums?);                          // [1, 2, 3, 4, 5]

    Ok(())
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.