[Pre-RFC] Add FromIterator impl for HashMap<K, Vec<V>>


This RFC proposes a new FromIterator<(K, V)> implementation for HashMap<K, Vec<V>>.


It's relatively common to want to group a list of values over some specific key. The current method of doing this either requires a third party crate or manually constructing the HashMap in a for loop, making use of the Entry API.

This is common enough that I was surprised not to see an ergonomic approach using collect. This RFC proposes adding an impl to make this possible.


As an example, imagine you had a list of books, and wanted to group the books by the author that wrote them.

Current Implementation

let mut books_by_author: HashMap<&str, Vec<&Book>> = HashMap::new();  
for book in &books {  

With This RFC

let books_by_author: HashMap<&str, Vec<&Book>> =
    books.iter().map(|book| (book.author, book)).collect();

Future Considerations

  • Instead of adding this implementation for just Vec<V>, we could consider adding it for all collections C: Default + Extend<V>, extending this functionality to all collections, such as a HashSet.

Prior Art


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.