rust-lang / rust-lang/rfcs

Proposal: Add FromIterator impl for HashMap<K, Vec<V>>

Open
#3,351 7 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

Summary

I'm proposing a small quality of life improvement, that I was surprised to find wasn't already a part of the language.
I want to introduce a new FromIterator<(K, V)> implementation for HashMap<K, Vec<V>>.

I'm happy to create a PR for this if we want to move forward.

Note: I tried asking this on internals, without any responses, so am hoping to get more traction here.

Motivation

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.

Example

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 {  
    books_by_author.entry(book.author).or_default().push(book);  
}
With This Proposal
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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the proposal's FromIterator<HashMap<K, Vec>> examples and compare the existing HashMap Entry API with the linked multimap and itertools prior art. Determine whether the narrow implementation or the broader Default + Extend design fits the RFC process; done means a resolved RFC direction rather than an implementation patch.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.