borrowing

Rust Borrow a map value through the entry API

The entry API is useful when updating a map value that may not exist yet. It combines lookup and possible insertion, then provides mutable access to the selected value. Use that access before other conflicting map operations. Expected output (not executed): 3 Why: The missing key receives zero, then its stored quantity increases to three. Common mistake: Holding the returned mutable reference across another map mutation and trying to use it afterward.

Formal Syntax & Structure

rust syntaxrust
map.entry(key).or_insert(default)

Working Example

Example Snippetrust
use std::collections::HashMap;fn main() {    let mut stock = HashMap::new();    let quantity = stock.entry("tea").or_insert(0);    *quantity += 3;    println!("{}", stock["tea"]);}
Rust Reference