typestar

Reshaping errors in Rust

map_err rewrites the error while leaving a successful value alone.

fn read_port(text: &str) -> Result<u16, String> {
    text.trim()
        .parse::<u16>()
        .map_err(|e| format!("bad port {text:?}: {e}"))
}

fn main() {
    match read_port(" 8080 ") {
        Ok(port) => println!("listening on {port}"),
        Err(msg) => println!("{msg}"),
    }
    println!("{:?}", read_port("http"));
    println!("{}", read_port("nope").unwrap_or_default());
}

How it works

  1. map_err is map for the error side.
  2. It is how you fit a library error into your own type.
  3. unwrap_or_default ends the chain without a panic.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
340
Tokens
117
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 3 of 4 in Result & the ? operator, step 6 of 15 in Error handling.

← Previous Next →