pub trait Hash {
// Required method
fn hash<H>(&self, state: &mut H)
where H: Hasher;
// Provided method
fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher,
Self: Sized { ... }
}Expand description
A hashable type.
Types implementing Hash are able to be hashed with an instance of
Hasher.
§Implementing Hash
You can derive Hash with #[derive(Hash)] if all fields implement Hash.
The resulting hash will be the combination of the values from calling
hash on each field.
#[derive(Hash)]
struct Rustacean {
name: String,
country: String,
}If you need more control over how a value is hashed, you can of course
implement the Hash trait yourself:
use std::hash::{Hash, Hasher};
struct Person {
id: u32,
name: String,
phone: u64,
}
impl Hash for Person {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
self.phone.hash(state);
}
}§Hash and Eq
When implementing both Hash and Eq, it is important that the following
property holds:
k1 == k2 -> hash(k1) == hash(k2)In other words, if two keys are equal, their hashes must also be equal.
HashMap and HashSet both rely on this behavior.
Thankfully, you won’t need to worry about upholding this property when
deriving both Eq and Hash with #[derive(PartialEq, Eq, Hash)].
Violating this property is a logic error. The behavior resulting from a logic error is not
specified, but users of the trait must ensure that such logic errors do not result in
undefined behavior. This means that unsafe code must not rely on the correctness of these
methods.