Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Structs as keys of a HashMap

  • struct

  • derive

  • Debug

  • Hash

  • Eq

  • PartialEq

  • We can also use structs as a keys in a HashMap, but for that we need to add a few traits.

use std::collections::HashMap;

#[derive(Debug, Hash, Eq, PartialEq)]
struct Person {
    fname: String,
    lname: String,
}

fn main() {
    let a = Person {
        fname: String::from("Steve"),
        lname: String::from("Jobs"),
    };

    let m = Person {
        fname: String::from("Bill"),
        lname: String::from("Gates"),
    };

    let mut lookup = HashMap::new();
    lookup.insert(a, "Apple");
    lookup.insert(m, "Microsoft");

    println!("{:?}", lookup);
}
{Person { fname: "Steve", lname: "Jobs" }: "Apple", Person { fname: "Bill", lname: "Gates" }: "Microsoft"}