unwrap and expect
- Rust course
- Beginner
- Lesson 110/115
- 4 min
Learn the unwrap and expect shortcuts and their risks.
unwrap and expect
unwrap() gives the value inside Ok/Some, otherwise it panics. expect("message") does the same, but you set the panic message; a message explaining why it shouldn't fail makes debugging easier:
let port: u16 = "8080".parse().expect("port sabiti geçerli olmalı");
// let x: i32 = "x".parse().unwrap();
// panic: called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }They are acceptable in prototypes, tests and truly impossible cases; they shouldn't be applied to user input in production code.
Non-panicking options
Ways of continuing with a default value:
let a: i32 = "x".parse().unwrap_or(0); // 0
let b: i32 = "".parse().unwrap_or_default(); // 0 (default for i32)
let c: i32 = "x".parse().unwrap_or_else(|_| -1); // -1
let d: Option<i32> = "x".parse().ok(); // Noneunwrap_or_else computes the default only when needed; it's preferred for an expensive default.
Practice Defaults
Do three conversions: expect("sayı olmalı") for "12", unwrap_or(0) for "x" and unwrap_or_default() for "" (all i32). Print the results separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let a: i32 = "12".parse().expect("sayı olmalı");
let b: i32 = "x".parse().unwrap_or(0);
let c: i32 = "".parse().unwrap_or_default();
println!("{} {} {}", a, b, c);
}Expected output
12 0 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is most suitable when converting user input to a number?
- Handling the error with match or unwrap_or Correct answer
- unwrap()
- expect("hata")
- panic!
Explanation: User input is an expected source of errors; instead of crashing the program, the user should be informed.
2 Unwrap with a message
let port: u16 = "8080".parse().____("port sabiti geçerli olmalı");
let port: u16 = "8080".parse().expect("port sabiti geçerli olmalı");
Explanation: expect shows the given message on panic.
3 Method and result on "x" (i32)
| Term | Meaning |
|---|---|
unwrap() |
Panic |
unwrap_or(0) |
0 |
unwrap_or_else(|_| -1) |
-1 |
ok() |
None |