vectorrustcombinationsrust-itertools

Combining Two Vectors of References into a Vector of Values Without Consuming an Iterator in Rust


I'm currently working with Rust and I'm trying to combine two vectors of references into a single vector of values, without consuming an iterator.

Here's the situation: I'm generating vectors by iterating over specific combinations (2 elements from one vector, 2 elements from another vector).

Here's the code I'm currently working with:

use core::iter::Iterator;
use itertools::Itertools;

fn main() {
    let vec_a: Vec<u8> = vec![1, 2, 3];
    let vec_b: Vec<u8> = vec![4, 5, 6];

    // a: Vec<&u8>
    for a in vec_a.iter().combinations(2) {
        // b: Vec<&u8>
        for b in vec_b.iter().combinations(2) {
            // c: Vec<u8> <- a + b
            let c: Vec<u8> = a.clone().into_iter().chain(b).cloned().collect();
            println!("a: {:?}, b: {:?}, c: {:?}", a, b, c);
        }
    }
}

The expected output is as follows:

a: [1, 2], b: [4, 5], c: [1, 2, 4, 5]
a: [1, 2], b: [4, 6], c: [1, 2, 4, 6]
a: [1, 2], b: [5, 6], c: [1, 2, 5, 6]
a: [1, 3], b: [4, 5], c: [1, 3, 4, 5]
a: [1, 3], b: [4, 6], c: [1, 3, 4, 6]
a: [1, 3], b: [5, 6], c: [1, 3, 5, 6]
a: [2, 3], b: [4, 5], c: [2, 3, 4, 5]
a: [2, 3], b: [4, 6], c: [2, 3, 4, 6]
a: [2, 3], b: [5, 6], c: [2, 3, 5, 6]

I've reviewed the following StackOverflow post: Best way to concatenate vectors in Rust, but the solution provided there consumes the Vec and its iterator, which doesn't work in my case.

Could anyone provide guidance on how to combine these vectors of references into a vector of values without consuming the iterator? Any insights or suggestions would be greatly appreciated.


Solution

  • Thanks to @ChayimFriedman, the issue was resolved by using the copied() method twice in the chain. The copied() method creates an iterator that copies the elements of the original iterator. In this case, it's used to copy the references from the original vectors a and b into the new vector c.

    Here's the corrected code:

    // a: Vec<&u8>
    // b: Vec<&u8>
    
    let c: Vec<u8> = a.iter().chain(&b).copied().copied().collect();
    println!("a: {:?}", a);
    println!("b: {:?}", b);