match and Result
- Rust course
- Beginner
- Lesson 109/115
- 4 min
Handle both arms of a Result with match.
match and Result
match is used to handle the error on the spot. By adding guards to the arms, successful values can be classified further:
match "8".parse::<i32>() {
Ok(n) if n >= 0 => println!("kare: {}", n * n),
Ok(n) => println!("negatif: {n}"),
Err(e) => println!("hata: {e}"),
}In the Err(e) arm, printing e with {} gives a user-friendly message (Display), while {:?} gives developer-oriented detail (Debug).
Result helpers
As with Option, Result has methods that work without writing a match:
let r: Result<i32, String> = Ok(3);
r.is_ok() // true
r.ok() // Some(3): Result → Option
r.map(|n| n + 1) // Ok(4)
r.and_then(|n| if n > 5 { Ok(n) } else { Err("küçük".into()) }) // Err("küçük")and_then chains the success value into a next step that may fail.
Practice Classify inputs
Loop over the inputs ["8", "-3", "abc"] and handle the result of parse::<i32>() with match: print kare: N for a non-negative number, negatif: N for a negative one and hata: MESAJ for an error.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
for g in ["8", "-3", "abc"] {
match g.parse::<i32>() {
Ok(n) if n >= 0 => println!("kare: {}", n * n),
Ok(n) => println!("negatif: {}", n),
Err(e) => println!("hata: {}", e),
}
}
}Expected output
kare: 64 negatif: -3 hata: invalid digit found in string
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What appears when the error of <code>"".parse::<i32>()</code> is printed with <code>{}</code>?
- None
- cannot parse integer from empty string Correct answer
- invalid digit found in string
- ParseIntError { kind: Empty }
Explanation: The Display message is for humans; the Debug form would be ParseIntError { kind: Empty }.
2 The error arm
match "x".parse::<i32>() {
Ok(n) => println!("{n}"),
____(e) => println!("hata: {e}"),
}
match "x".parse::<i32>() {
Ok(n) => println!("{n}"),
Err(e) => println!("hata: {e}"),
}
Explanation: Result's error variant is Err.
3 Method and result on Ok(3)
| Term | Meaning |
|---|---|
is_ok() |
true |
ok() |
Some(3) |
map(|n| n + 1) |
Ok(4) |
is_err() |
false |