Skip to content

.or_insert_default() for collections' Entry #44788

Closed
@lukaslueg

Description

@lukaslueg

Option (since 1.0) and Result(since 1.16) have a handy .unwrap_or_default() for every type that is Default. The collection types have .or_insert() and .or_insert_with() but no .or_insert_default(). This would be nice to have and would free people from writing things like .or_insert_with(HashSet::new) multiple times.

Something along the line of

use std::collections::hash_map::{HashMap, Entry};

struct DefaultedEntry<'a, K:'a, V:'a> (Entry<'a, K, V>);

impl<'a, K:'a, V:'a + Default> DefaultedEntry<'a, K, V> {
    fn or_insert_default(self) -> &'a mut V {
        match self.0 {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(Default::default()),
        }
    }
}

fn main() {
    let foos = [("foo", "bar"), ("foobar", "ping"), ("foo", "barfoo")];

    let mut foomap: HashMap<_, Vec<_>> = HashMap::new();
    for &(ref foo, ref bar) in &foos {
        DefaultedEntry(foomap.entry(foo)).or_insert_default().push(bar);
    }

    println!("{:?}", foomap);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions