std-method
Option::insert / get_or_insert / get_or_insert_with / get_or_insert_default
insert replaces any prior payload. The get_or_insert family preserves a present payload and fills an empty slot. The closure variant builds the fallback only when needed. Each returns a mutable reference. Expected stdout (not executed): Some(9) Common mistake: Expecting get_or_insert to overwrite existing data.
Formal Syntax & Structure
rust syntaxrust
fn insert(&mut self, value: T) -> &mut T; fn get_or_insert(&mut self, value: T) -> &mut T; fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T; fn get_or_insert_default(&mut self) -> &mut T where T: DefaultWorking Example
Example Snippetrust
fn main() { let mut slot = None; *slot.get_or_insert_with(|| 4) += 1; slot.insert(9); println!("{slot:?}");}