I have the following:
enum SomeType {
VariantA(String),
VariantB(String, i32),
}
fn transform(x: SomeType) -> SomeType {
// very complicated transformation, reusing parts of x in order to produce result:
match x {
SomeType::VariantA(s) => SomeType::VariantB(s, 0),
SomeType::VariantB(s, i) => SomeType::VariantB(s, 2 * i),
}
}
fn main() {
let mut data = vec![
SomeType::VariantA("hello".to_string()),
SomeType::VariantA("bye".to_string()),
SomeType::VariantB("asdf".to_string(), 34),
];
}
I would now like to call transform
on each element of data
and store the resulting value back in data
. I could do something like data.into_iter().map(transform).collect()
, but this will allocate a new Vec
. Is there a way to do this in-place, reusing the allocated memory of data
? There once was Vec::map_in_place
in Rust but it has been removed some time ago.
As a work-around, I've added a Dummy
variant to SomeType
and then do the following:
for x in &mut data {
let original = ::std::mem::replace(x, SomeType::Dummy);
*x = transform(original);
}
This does not feel right, and I have to deal with SomeType::Dummy
everywhere else in the code, although it should never be visible outside of this loop. Is there a better way of doing this?