Unwrap and Expect
Quick error handling with unwrap and expect.
Unwrap and Expect
Quick error handling with unwrap and expect.
Difficulty
Beginner
Code
fn main() {
// unwrap: panics with default message
let home: std::net::IpAddr = "127.0.0.1".parse().unwrap();
println!("{}", home);
// expect: panics with custom message
let port: u16 = "8080".parse().expect("port should be a number");
println!("{}", port);
// Option unwrap
let x: Option<i32> = Some(5);
let y: i32 = x.unwrap();
println!("{}", y);
}Explanation
unwrap() panics on None/Err. expect() adds custom message.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.