std-method

btree_map::Entry::or_default

Initialize a missing record from its type default. For Vec this gives an empty vector, suitable for grouping. Expected stdout (not executed): [7, 9] Common mistake: Expecting Default to reset a present value.

Formal Syntax & Structure

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

Working Example

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