Result represents either Ok(value) or Err(error). Matching both cases makes the success and failure paths explicit.

Program

Play the program to parse selected text and build a label from the Result.

text
result_match.rs
Replay: real traced execution (multi-file project)
fn main() {
    let text = "42";
    let parsed = text.parse::<i32>();
    let label = match parsed {
        Ok(value) => format!("ok:{value}"),
        Err(_) => "error".to_string(),
    };
    println!("{label}");
}
fn main() {
    let text = "7";
    let parsed = text.parse::<i32>();
    let label = match parsed {
        Ok(value) => format!("ok:{value}"),
        Err(_) => "error".to_string(),
    };
    println!("{label}");
}
fn main() {
    let text = "bad";
    let parsed = text.parse::<i32>();
    let label = match parsed {
        Ok(value) => format!("ok:{value}"),
        Err(_) => "error".to_string(),
    };
    println!("{label}");
}
  1. text ← "42", parsed ← Ok(42), label ← "ok:42"

    1fn main() {2    let tex→ "42"t = "42"; //@text="42", "7", "bad"3    let parse→ Ok(42)d = text.parse::<i32>();4    let labe→ "ok:42"l = match parseOk(42)d {5        Ok(value) => format!("ok:{value}"),6        Err(_) => "error".to_string(),7    };8    println!("{label}");9}
    outputok:42
  1. text ← "7", parsed ← Ok(7), label ← "ok:7"

    1fn main() {2    let tex→ "7"t = "7";3    let parse→ Ok(7)d = text.parse::<i32>();4    let labe→ "ok:7"l = match parseOk(7)d {5        Ok(value) => format!("ok:{value}"),6        Err(_) => "error".to_string(),7    };8    println!("{label}");9}
    outputok:7
  1. text ← "bad", parsed ← Err(ParseIntError { kind: InvalidDigit })

    1fn main() {2    let tex→ "bad"t = "bad";3    let parse→ Err(ParseIntError { kind: InvalidDigit })d = text.parse::<i32>();4    let labe→ "error"l = match parseErr(ParseIntError { kind: InvalidDigit })d {5        Ok(value) => format!("ok:{value}"),6        Err(_) => "error".to_string(),7    };8    println!("{label}");9}
    outputerror

Follow the Match

  1. The program tries to parse selected text.
  2. The parse produces one Result.
  3. Ok(value) builds the success label.
  4. Err(_) builds the failure label. | Arm | What the page shows | | --- | --- | | Ok(value) | Use the parsed value. | | Err(_) | Keep the program moving with a stable message. |
Result `Result<T, E>` is either `Ok(T)` or `Err(E)`.
match `match parsed` handles both success and error cases.
error path The `Err(_)` arm ignores the error detail and returns a stable label.

Exercise: result_match.rs

Match a parse Result and produce one label for success and one stable label for failure