How to Use unwrap_or, unwrap_or_else, and unwrap_or_default

Use unwrap_or for static defaults, unwrap_or_else for error handling, and unwrap_or_default for types with a Default implementation.

Use unwrap_or for a static default, unwrap_or_else for expensive or error-handling logic, and unwrap_or_default when the type implements Default.

use std::collections::HashMap;
use std::process;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);

// Static default value
let score = scores.get(&"Blue").copied().unwrap_or(0);

// Expensive computation or error handling
let config = Config::build(&args).unwrap_or_else(|err| {
    println!("Problem parsing arguments: {err}");
    process::exit(1);
});

// Default trait implementation
let default_score: Option<i32> = None;
let final_score = default_score.unwrap_or_default();

struct Config { query: String, file_path: String } impl Config { fn build(_args: &[String]) -> Result<Config, &'static str> { Ok(Config { query: String::new(), file_path: String::new() }) } }