Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.or_insert_default() for collections' Entry #44788

Closed
lukaslueg opened this issue Sep 23, 2017 · 2 comments
Closed

.or_insert_default() for collections' Entry #44788

lukaslueg opened this issue Sep 23, 2017 · 2 comments

Comments

@lukaslueg
Copy link
Contributor

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);
}
@kennytm
Copy link
Member

kennytm commented Sep 23, 2017

Duplicate of #44324, and already implemented in #44344! 😃 (The method name is or_default.)

@lukaslueg
Copy link
Contributor Author

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants