liveBook · Manning

Unwrap_or

As explained in Learn Rust in a Month of Lunches

unwrap_or is a Rust method that returns an Option or Result value when present or successful and otherwise returns a specified fallback value without panicking.

unwrap_or returns the contained value when an Option has one; when it contains None, it returns the fallback you provide. Unlike unwrap, it does not panic. section 6.3

Use zero when an index is missing

let my_vec = vec![8, 9, 10]; let fourth = my_vec.get(3).unwrap_or(&0); println!("{fourth}"); The lookup finds no fourth item, so unwrap_or returns a reference to 0. The program prints 0 instead of panicking. section 6.3

fn main() {
    let my_vec = vec![8, 9, 10];
 
    let fourth = my_vec.get(3).unwrap_or(&0);    #1
    println!("{fourth}");
}

Inspect the complete vector lookup and fallback example. section 6.3

Choose unwrap_or when a sensible default is better than stopping the program. The fallback should represent what your program should do when the expected value is absent. section 6.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Demonstrates fallback behavior with vector lookup and stops short of broader Option design.
Examples
Uses a missing fourth vector element and returns 0 through unwrap_or(&0).
What you can do after
Apply it via Rust's Option API to choose a fallback instead of panicking.
How it connects
Connects Option lookup with unwrap, expect, panic, and vector indexing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.