std-method

Entry::or_default

Borrow the existing value or initialize a vacant entry using V::default(). Useful for counters and grouped vectors. The default depends on the type. Expected stdout (not executed): ["Neda", "Ali"] Common mistake: Assuming every type implements Default or that default means a valid business value.

Formal Syntax & Structure

rust syntaxrust
pub fn or_default(self) -> &'a mut V where V: Default

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();    groups.entry("design").or_default().push("Neda");    groups.entry("design").or_default().push("Ali");    println!("{:?}", groups["design"]);}
Rust Reference