I am working with sets of pairs of integers in Rust using HashSet<(usize, usize)>
, and my goal is to compute a set HashSet<usize>
which contain all nodes appearing in those pairs. Essentially, this is a flatten
operation.
Let's suppose variable set: HashSet<(usize, usize)>
contains the initial set of pairs. My first attempt to compute the flattened version was:
let res: HashSet<usize> = set.iter().flatten().collect()
however I encounter the error: "&(usize, usize)
is not an iterator the trait Iterator
is not implemented for &(usize, usize)
required for &(usize, usize)
to implement IntoIterator
. Required by a bound in flatten
."
I thought the issue was that the iterator was over references so I also tried using into_iter
instead, but I get the same error message, this time saying "(usize, usize)
is not an iterator..."
I do have a piece of code that works fine using a for
loop and the push
operation, but I would like to do it in a more functional way with flatten
.
Simply convert the tuple to an array, which is iterable:
let res: HashSet<usize> = set.iter().flat_map(|&(a, b)| [a, b]).collect();