WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 21 of 100

What are the differences between the panic! macro and the unwrap function?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

Both the ‘panic!‘ macro and the ‘unwrap‘ function are used in error handling in Rust programming. However, there are some key differences between the two.

- The ‘panic!‘ macro is used to immediately stop program execution and print an error message to the console when the code reaches an unrecoverable error state. This essentially crashes the program and is usually used as a last resort when a program cannot continue executing. Here’s an example:

    let x = vec![1, 2, 3];
    println!("The fourth element: {}", x[3]); // this will cause a panic and crash the program

- The ‘unwrap‘ function, on the other hand, is used to get the value of a ‘Result‘ or an ‘Option‘ enum. It either returns the value if it exists, or it panics with a default error message if it doesn’t. Here’s an example:

    let x = Some("hello world");
    let y = x.unwrap(); // y is "hello world"
    
    let z: Result<i32, &str> = Err("error message");
    let w = z.unwrap(); // this will cause a panic with the error message "called `Result::unwrap()` on an `Err` value: error message"

In summary, ‘panic!‘ is used to handle unrecoverable errors when the program cannot continue execution, while ‘unwrap‘ is used to handle recoverable errors where you expect the result to be successful most of the time. Nonetheless, both should be used sparingly and deliberately. Whenever possible, it is often better to use ‘match‘ expressions, ‘if let‘ or ‘expect‘ functions to handle errors in a more precise and controlled way.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics