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
}
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):