How to create a set of objects in Rust

1 Answer

0 votes
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

#[derive(Debug, Eq)]
struct Person {
    name: String,
    age: u32,
}

// Implement the Hash trait for custom struct
impl Hash for Person {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.age.hash(state);
    }
}

// Implement PartialEq to allow comparisons
impl PartialEq for Person {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.age == other.age
    }
}

fn main() {
    let mut people_set = HashSet::new();

    people_set.insert(Person { name: "Robert".to_string(), age: 45 });
    people_set.insert(Person { name: "Jennifer".to_string(), age: 38 });
    people_set.insert(Person { name: "Sharon".to_string(), age: 51 });
    people_set.insert(Person { name: "Robert".to_string(), age: 45 }); // Duplicate, won't be added

    // Print the unique elements in the set
    for person in &people_set {
        println!("{:?}", person);
    }
}



/*
run:

Person { name: "Robert", age: 45 }
Person { name: "Jennifer", age: 38 }
Person { name: "Sharon", age: 51 } 

*/

 



answered Apr 22 by avibootz
...