RRust By Example

Unwrap and Expect

Quick error handling with unwrap and expect.

Unwrap and Expect

Quick error handling with unwrap and expect.

Difficulty

Beginner

Code

rust
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

This example demonstrates how to use unwrap and expect in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the error-handling category to build a complete understanding of this topic.

More Error Handling Examples