"to owned" nested structures

Hi, I have a function that accumulates a HashSet<Vec<&(usize, &i32)>. I want the function to return a HashSet<Vec<(usize, i32)>>. In a word, I want to transfer the ownership of the tuples and of the second item of each tuple.

In cases like this, how to "copy all the levels of a nested structure"? Is this idiomatic or I should implement a different solution? The function is the following:

fn put_eggnod_in_containers(liters: i32, container_sizes: &[i32]) -> HashSet<Vec<(usize, i32)>> {
    let container_sizes: Vec<_> = container_sizes.iter().enumerate().collect();

    let mut combinations = HashSet::new();

    for n in 1..=container_sizes.len() {
        for combination in container_sizes.combination(n) {
            let sum: i32 = combination.iter().map(|c| c.1).sum();
            if sum == liters {
                combinations.insert(combination);
            }
        }
    }

    combinations // ERROR: expected `std::collections::HashSet<std::vec::Vec<(usize, i32)>>` because of return type
}

Thanks! :slight_smile:

You'd do something like this:

let container_sizes: Vec<_> = container_sizes.iter().copied().enumerate().collect();
for n in 1..container_sizes.len() {
    for combination in container_sizes.combination(n) {
        let sum: i32 = combination.iter().map(|x| x.1).sum();
        if sum == liters {
            combinations.insert(combination);
        }
    }
}

Note my use of .copied, this is what makes it work, because it takes an iterator over &T and when T: Copy, performs *value, therefore copying it.

Also, using code in your post, please put it in code fences and not indentation (Code fences allow for highlighting):

```
like this
```
1 Like

Hi! Thanks, I reformatted my code.

The following line doesn't work though: no method named "copied" found for type "std::vec::Vec<(usize, i32)>" in the current scope

Whoops, I made an error. I've corrected for it above.

Thanks for the edit. The code still returns HashSet<Vec<&(usize, i32)>> instead of HashSet<Vec<(usize, i32)>>

I've seen that I can solve my problem at hand with

combinations.into_iter().map(|v| v.into_iter().copied().collect()).collect()

But is all this plethora of copied, collect, ìnto_iter`... idiomatic Rust?

Normally you wouldn't store references in the first place, but this is the idiomatic way to convert them once you've got them.

2 Likes