Macro slotmap::new_key_type
source · macro_rules! new_key_type { ( $(#[$outer:meta])* $vis:vis struct $name:ident; $($rest:tt)* ) => { ... }; () => { ... }; }
Expand description
A helper macro to create new key types. If you use a new key type for each slot map you create you can entirely prevent using the wrong key on the wrong slot map.
The type constructed by this macro is defined exactly as DefaultKey
,
but is a distinct type for the type checker and does not implicitly convert.
§Examples
new_key_type! {
// A private key type.
struct RocketKey;
// A public key type with a doc comment.
/// Key for the user slot map.
pub struct UserKey;
}
fn main() {
let mut users = SlotMap::with_key();
let mut rockets = SlotMap::with_key();
let bob: UserKey = users.insert("bobby");
let apollo: RocketKey = rockets.insert("apollo");
// Now this is a type error because rockets.get expects an RocketKey:
// rockets.get(bob);
// If for some reason you do end up needing to convert (e.g. storing
// keys of multiple slot maps in the same data structure without
// boxing), you can use KeyData as an intermediate representation. This
// does mean that once again you are responsible for not using the wrong
// key on the wrong slot map.
let keys = vec![bob.data(), apollo.data()];
println!("{} likes rocket {}",
users[keys[0].into()], rockets[keys[1].into()]);
}