Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over combinations of elements of a vector and manipulate elements

Tags:

rust

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?

like image 910
Iniesta8 Avatar asked Oct 25 '25 16:10

Iniesta8


1 Answers

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.

like image 120
edwardw Avatar answered Oct 27 '25 09:10

edwardw