Crate automap[][src]

A simple pattern to implement maps where the value type also contains the key type. Implementations for HashMap and BTreeMap from std::collections are provided.

use std::collections::HashMap;
use automap::{AutoHashMap, AutoMapped};

// Let's say we want a `Person` to be keyed by their `name` in a HashMap
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Person {
    name: String,
    age: u16,

// We can specify how to derive the key from the value
// As long as the Key type meets the bounds for a normal HashMap key, we
// can use this value in an AutoHashMap.
// (Similarly for BTreeMap.)
impl AutoMapped for Person {
    type Key = String;

    fn key(&self) -> &Self::Key {

// Then, we can simply use an `AutoHashMap` to insert values directly.
let mut map = AutoHashMap::new();
let michelle = Person { name: "Michelle".into(), age: 37 };

// You can access all other normal HashMap methods directly:
assert_eq!(map.get("Michelle".into()), Some(&michelle));
assert_eq!(map.remove("Michelle".into()), Some(michelle));

// We can also go From and Into a normal HashMap easily.
let inner: HashMap<_, _> = map.into();
let map: AutoHashMap<_> = inner.into();



A map whose values also contain their keys


A map whose values also contain their keys



The constraints on an AutoBTreeMap key


The constraints on an AutoHashMap key


Trait that describes how to extract a key out of a value