'Cast HashMap to Vector
Is there a way to cast HashMap to Vector in Rust w/o copying the elements, i.e. move data from hash map to vector? By using iter+map+collect requires to copy all elements of hash map, which is non-optimal as hash map is not assumed to used further. In case of Option it works pretty well, as data it moved automatically and we can use as_ref to prevent it.
Code example where I have to copy all elements
use std::collections::HashMap;
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
struct base1 {
x: i32,
}
#[derive(Clone, Debug)]
struct base2 {
x: i32,
}
#[derive(Debug)]
struct ss {
x: base1,
y: base2,
}
fn main() {
let mut map = HashMap::new();
map.insert(base1 { x: 13 }, base2 { x: 13 });
let vec: Vec<ss> = map
.iter()
.map(|x| ss {
x: x.0.clone(),
y: x.1.clone(),
})
.collect();
println!("Ma13: {:?}", vec);
}
Solution 1:[1]
There is no way to reuse the memory as HashMap is laid out in memory differently than Vec. However, if you don't need the map anymore, you don't need to clone, and you can instead use into_iter():
let vec: Vec<ss> = map.into_iter().map(|x| ss { x: x.0, y: x.1 }).collect();
There will be no difference with your example since i32 is zero-cost to clone, but for e.g. String it'll make a difference.
You can shorten it even more:
let vec: Vec<ss> = map.into_iter().map(|(x, y)| ss { x, y }).collect();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sven Marnach |
