I have the piece of code below, which works fine, but I am a bit bothered by the need for clone
inside the for loop. In principle, the vector is no longer needed after a.clear()
is called, so it could be consumed inside this loop, but the code won’t compile without clone
. Is there a clever way around this, that moves self.a[i].v
into the new AStruct
instead of cloning it?
use std::collections::HashMap;
#[derive(Debug)]
struct AStruct {
v: Vec<i32>,
w: i32,
}
struct TestStruct {
a: Vec<AStruct>,
}
impl TestStruct {
fn test(&mut self) {
let mut h: HashMap<Vec<i32>, i32> = HashMap::new();
for x in &self.a {
let key = x.v.clone();
let entry = h.entry(key).or_insert(0);
*entry += x.w;
}
self.a.clear();
for (key, value) in h {
self.a.push( AStruct {
v: key,
w: value,
} );
}
}
}
fn main() {
let a = AStruct {
v: vec![1, 2, 3],
w: 4,
};
let mut t = TestStruct { a: vec![a] };
t.test();
println!("{:?}", t.a);
}