Result and unwrap

Rust does not use exceptions. Functions that can fail communicate that failure through their return type.

Result<T, E>

#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),   // success — contains the value
    Err(E),  // failure — contains the error
}
}

A function returning Result forces the caller to handle both cases. Window::new() from the minifb crate is a typical example — opening a window can fail if the display server is not available.

Handling a Result

#![allow(unused)]
fn main() {
// explicit match
match Window::new("CHIP-8", width, height, options) {
    Ok(w)  => { /* use w */ },
    Err(e) => eprintln!("error: {}", e),
}

// if let — only handle the success case
if let Ok(w) = Window::new("CHIP-8", width, height, options) {
    // use w
}
}

unwrap()

unwrap() extracts the Ok value — or panics if the result is Err:

#![allow(unused)]
fn main() {
let window = Window::new("CHIP-8", WIDTH * SCALE, HEIGHT * SCALE, options)
    .unwrap();
}

This is acceptable when:

  • Failure is truly unexpected (a programming error, not user input)
  • You are prototyping and will add proper error handling later

It is not acceptable in production code where the error is recoverable.

Option<T>

The same idea for values that may or may not exist:

#![allow(unused)]
fn main() {
enum Option<T> {
    Some(T),  // value is present
    None,     // value is absent
}
}
#![allow(unused)]
fn main() {
let v = vec![1, 2, 3];
v.get(0)  // Some(&1)
v.get(9)  // None — no panic, unlike v[9]
}

The ? operator

In functions that return Result, ? propagates errors upward instead of unwrapping:

#![allow(unused)]
fn main() {
fn setup() -> Result<Window, minifb::Error> {
    let window = Window::new("CHIP-8", WIDTH, HEIGHT, options)?;
    // if Err → returns early with the error
    // if Ok  → window is the unwrapped value
    Ok(window)
}
}

? is the idiomatic alternative to unwrap() in production code.


In the emulator: unwrap() is used in main.rs when creating the window and updating the pixel buffer — failures there mean the window cannot be opened, and panicking is an acceptable response for this project. See The Main Loop.