Skip to main content

Parsing text safely

`parse` is generic over the target type, so you either annotate the binding or use the turbofish: `"42".parse::<i32>()`. It returns a `Result`, because text from the outside world is not to be trusted.

Every real program has this boundary. Handling it explicitly at the edge means the rest of your code can work with plain `i32` values that are known to be valid.

`unwrap_or_default`, `filter_map` and `?` all keep the happy path readable while the failure case stays handled.

parse with no target type

fn main() {
    let n = "42".parse(); // error[E0282]
    println!("{n:?}");
}

error[E0282]: type annotations needed

Say what to parse into: `let n: Result<i32, _> = "42".parse();` or `"42".parse::<i32>()`.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust