Is it possible to write a function which modifies a struct member in place such that one can use it with both Vec and HashMap::values() ?
This is what I came up so far:
use std::collections::HashMap;
struct Foo {
x: i32,
}
fn process_collection<T>(collection: &mut T)
where
T: IntoIterator<Item = Foo>,
for<'a> &'a mut T: IntoIterator<Item = &'a mut Foo>,
{
for item in collection.into_iter() {
item.x = 5;
}
}
fn main() {
let mut numbers = vec![Foo { x: 1 }, Foo { x: 2 }];
// Set all .x members to 5.
process_collection(&mut numbers);
for item in &numbers {
println!("item after: {}", item.x);
}
let mut data: HashMap<String, Foo> = HashMap::new();
data.insert("One".to_string(), Foo {x: 1} );
data.insert("Two".to_string(), Foo {x: 2});
// This does not compile.
process_collection(&mut data.values());
}
valuesiterates over immutable references to the values, you have to usevalues_mutif you need exclusive references to be able to mutate the values.Additionally writing out the mutable reference in
&mut Tis extremely limiting and does not allowValuesMut(an iterator over mutable references to the values) at all (neither does it implementIntoIterator, instead just takeT: IntoIterator<&mut Foo>: