std-method

Rust HashMap Entry::or_insert(): get or initialize a value

This method consumes the Entry handle, inserts default only when its key is absent, and returns a mutable reference to the stored value. The default argument itself is evaluated even if insertion is unnecessary; or_insert_with is useful for lazy construction. Expected output (not executed): 5 3 Why: book retains its existing value before incrementing; pen starts with the supplied default. Common mistake: Thinking or_insert overwrites an occupied entry or lazily evaluates its default expression.

Formal Syntax & Structure

rust syntaxrust
pub fn or_insert(self, default: V) -> &'a mut V

Parameters & Attributes

NameTypeDescription
defaultVValue inserted if the entry is vacant; evaluated eagerly.

Return Value

&'a mut V

Exclusive reference to the stored value, tied to the map borrow.

Working Example

Example Snippetrust
use std::collections::HashMap;fn main() {    let mut counts = HashMap::from([("book", 4)]);    *counts.entry("book").or_insert(99) += 1;    *counts.entry("pen").or_insert(2) += 1;    println!("{} {}", counts["book"], counts["pen"]);}
Rust Reference