Rust 1.99 (2024 edition) reference · Option and Result

Rust Result::map_err, unwrap_or_else and ok Method

Convert or recover from errors: change the error type, fall back to a value, or discard the error as an Option.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn map_err<F>(self, op: O) -> Result<T, F>   fn unwrap_or_else(self, op: F) -> T   fn ok(self) -> Option<T>

Parameters

ParameterDescription
map_err Change the error, e.g. add context.
map Change the Ok value.
unwrap_or_else Recover with a function of the error.
ok() Result to Option.
is_ok / is_err Check without consuming.

Examples

Example 1
fn main() {
    let r: Result<u16, String> = "70000".parse::<u16>().map_err(|e| format!("bad port: {e}"));
    println!("{r:?}");
    let port = "abc".parse::<u16>().unwrap_or_else(|_| 8080);
    println!("{port}");
    println!("{:?}", "12".parse::<u8>().ok());
}

Output

Err("bad port: number too large to fit in target type")
8080
Some(12)

Run this on your computer — see “Get Started” for setup.

Collecting Results
fn main() {
    let inputs = ["1", "two", "3"];
    let (ok, bad): (Vec<_>, Vec<_>) = inputs.iter().map(|s| s.parse::<i32>()).partition(|r| r.is_ok());
    println!("{} ok, {} bad", ok.len(), bad.len());
    let all: Result<Vec<i32>, _> = ["1", "2"].iter().map(|s| s.parse::<i32>()).collect();
    println!("{all:?}");
}

Output

2 ok, 1 bad
Ok([1, 2])

Run this on your computer — see “Get Started” for setup.

Was this page helpful?