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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With