typestar

Panic or Result in Rust

Panics are for bugs; Results are for conditions your caller can handle.

fn parse_index(text: &str, len: usize) -> Option<usize> {
    let idx: usize = text.parse().ok()?;
    if idx < len {
        Some(idx)
    } else {
        None
    }
}

fn main() {
    let items = ["a", "b", "c"];
    assert!(!items.is_empty(), "need at least one item");

    println!("{:?}", parse_index("1", items.len()));
    println!("{:?}", parse_index("9", items.len()));

    let config: Option<&str> = Some("dark");
    println!("{}", config.expect("theme is always set"));
}

How it works

  1. expect panics with your message when the bug is yours.
  2. assert! documents an invariant and checks it.
  3. unwrap_or keeps going where a panic would be rude.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
430
Tokens
158
Three-star pace
105 tpm

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

Type this snippet

Step 1 of 2 in Panics & recovery, step 13 of 15 in Error handling.

← Previous Next →