Enums with data as HashMap keys

Published 193d ago

 ayebear

Arbitrary types can be used as HashMap keys, as long as they implement the appropriate traits which can usually be auto-derived.

use std::collections::HashMap;

#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Key {
    Position(i32, i32),
    Name(String),
    Group(Vec<Key>),
}

fn main() {
    let mut map = HashMap::new();
    map.insert(Key::Position(5, 3), 1);
    map.insert(Key::Name("Foo".into()), 2);
    map.insert(
        Key::Group(vec![Key::Position(0, 1), Key::Name("Bar".into())]),
        3,
    );
    println!("Map: {map:?}");
}

hashmapenum
0

Please login or sign up to comment and collaborate