Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to create a HashMap from Vector fields

Tags:

rust

Let's say we have a vector of structs:

struct Item {
    id: u32,
    name: String,
    // ...
}

let mut items: Vec<Item> = vec!(
    Item { id: 54, name: "Foo".into() },
    Item { id: 87, name: "Bar".into() });

What is the most efficient way to create a HashMap that looks like this:

{87: "Bar", 54: "Foo"}

?

By "efficient", in this case I mostly mean "less verbose". Why? Because I feel in most real-world cases a slight performance penalty wouldn't really matter. But when it does matter, one can always resort to HashMap::with_capacity() and a simple loop, for example. Nonetheless, all else equal, I would of course prefer a solution that is faster and uses less memory.

The simplest thing I could come up with was:

let temp_tuples = items.iter().map(|x| (x.id, x.name.clone())).collect::<Vec<_>>();
let map_names_by_id: HashMap<_, _> = temp_tuples.into_iter().collect();

That surely isn't the most performant solution, as it creates a temporary vector of tuples, but as I said, I mostly care about convenience & brevity in this case. So, is there something simpler than that?

like image 502
at54321 Avatar asked Sep 15 '25 21:09

at54321


1 Answers

There's no need to collect to a Vec in between:

let map_names_by_id: HashMap<_, _> =
    items.iter().map(|x| (x.id, x.name.clone())).collect();
like image 167
orlp Avatar answered Sep 19 '25 08:09

orlp