Unwrap Or Default Supplies Fallbacks

Collapse None and Err into type defaults with unwrap_or_default: unwrap_or takes an explicit value and unwrap_or_else builds one lazily.

RustResilience

Code

rustsnippet
22 lines
fn main() {
    // None collapses into the type's Default value instead of panicking
    let empty: Option<u32> = None;
    println!("default u32: {}", empty.unwrap_or_default());

    let maybe = Some(String::from("config.toml"));
    println!("path: {}", maybe.unwrap_or_default());

    // Result works the same way: the Err branch takes Default
    let bad: Result<i32, String> = Err("parse failed".into());
    println!("default i32: {}", bad.unwrap_or_default());

    // unwrap_or takes an explicit value; unwrap_or_else builds one lazily through a closure that runs only when a value is missing
    let port: Option<u16> = None;
    println!("port: {}", port.unwrap_or(8080));
    let token = port.unwrap_or_else(fallback_token);
    println!("token: {token}");
}

fn fallback_token() -> u16 {
    49152
}

Inside the snippet

The working surface is the functions main and fallback_token — everything else is wiring.

Failure is encoded in the return type — Result leaves no room for an unhandled error.

Caveats

  • Nothing arrives from a registry; the language ships every API used.
  • Every fallible call yields a Result you must unwrap or propagate; there is no implicit throw.

Putting it to use

The primary signature is fn main()

The run emits 5 labeled sections — default u32:, path:, default i32:, port:, token: — one per step.

Start the program and main runs fallback_token one after another.

Core lines

let bad: Result<i32, String> = Err("parse failed".into());
let token = port.unwrap_or_else(fallback_token);
let maybe = Some(String::from("config.toml"));

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No panics — `Result` values carry the failure.
What does Unwrap Or Default Supplies Fallbacks print when run?
Running the file directly is enough — expect labeled output lines such as `default u32:`, `path:`, `default i32:`.