How to take difference of HashSet<u32> and HashSet<&_>?

i am trying to run this code

use std::collections::HashSet;
use std::io;

fn main() {
    let mut test_cases = String::new();
    io::stdin().read_line(&mut test_cases).expect("Invalid");

    let test_cases: i32 = test_cases.trim().parse().unwrap();

    for _ in 0..test_cases {
        let mut line = String::new();
        io::stdin().read_line(&mut line).expect("Invalid");

        let mut words = line.split(" ");

        let n: u32 = words.next().unwrap().trim().parse().unwrap();
        let m: u32 = words.next().unwrap().trim().parse().unwrap();
        let k: u32 = words.next().unwrap().trim().parse().unwrap();

        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Invalid");

        let mut ignored: HashSet<_> = input
            .split(" ")
            .map(|x| x.trim().parse().unwrap())
            .collect();

        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Invalid");

        let mut tracked: HashSet<_> = input
            .split(" ")
            .map(|x| x.trim().parse().unwrap())
            .collect();

        let mut total: HashSet<_> = (1..n + 1).collect();

        let it = ignored.intersection(&tracked);
        let un: HashSet<_> = ignored.union(&tracked).collect();
        let ui = total.difference(&un);
    }
}

but getting this error .


what should i do ?

You don't want un to be a HashSet<&u32>, so you should change your code such that it becomes an HashSet<u32> instead.

The reason that you got an HashSet<&u32> is that HashSet::union returns an iterator over references to the items in the HashSet. It does this so you don't have to destroy the two HashSets you are taking the union of, since for most types you cannot just get the actual value out of the HashSet.

To fix this, you can insert an .map(|my_ref| *my_ref), which converts the &u32 into an u32.

let un: HashSet<u32> = ignored.union(&tracked).map(|my_ref| *my_ref).collect();

Rust has a short-hand for this operation:

let un: HashSet<u32> = ignored.union(&tracked).copied().collect();
3 Likes

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.