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
