Is there a nicer way how to code difference of HashSets in a Vector?


I'm learning Rust on a Sudoku solver. Following code works fine for me, but I don't like the verbosity of last assignment to negated_rows. I believe there must be a shorter way.

let all_numbers_set: HashSet<u8> = (1..=9).collect();
let mut rows: Vec<_> = (0..9).map(|_| HashSet::<u8>::new()).collect();

// rows get populated here upon Sudoku solution progress

let negated_rows: Vec<HashSet<u8>> = rows
    .map(|c| all_numbers_set

You can use .copied() instead of .map(|x| *x) but other than that I don't think there's much you can change.

You can use (a - b) as a shorthand for a.difference(b).cloned().collect():

let negated_rows: Vec<HashSet<u8>> = rows
    .map(|c| &all_numbers_set - c)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.