I'd like to get all combinations of the elements of a vector. I'm using itertools' combinations() function. That's fine, but now I want to manipulate elements of the vector. Therefore I need an iterator that yields mutable references of the elements of the vector...
My code basically looks like follows:
let mut v: Vec<MyType> = vec![];
for vpair in v.iter_mut().combinations(2) {
vpair.first().unwrap().do_something(vpair.last().unwrap());
}
By calling do_something() I want to manipulate vpair.first().unwrap() and vpair.last().unwrap() on each iteration.
The error I receive is:
the trait std::clone::Clone is not implemented for &mut MyType
Can I somehow manage this issue or am I completely on the wrong track?
No, you can't do this. The itertools::Itertools::combinations is defined as
fn combinations(self, k: usize) -> Combinations<Self>
where
Self: Sized,
Self::Item: Clone,
It says the items of underlying iterator need to be Clone. After all, all combinations contain every item more than once by definition. But mutable reference never implements Clone since it is exclusive in Rust.
OTOH, if your MyType is itself Clone, you can try:
let mut v: Vec<MyType> = vec![];
for vpair in v.into_iter().combinations(2) {
vpair.first().unwrap().do_something(vpair.last().unwrap());
}
Since you own items returned from into_iter, you can do whatever you want with them. But every round of the loop manipulates independent clones of them, that may or may not be what you intend to do.
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