protocol Hashable<Self, H> { ... }
H: Hasher<H>
Types that can be hashed.
The hash method can be implemented directly or an automatic implementation can be mixed in using the DefaultHashable protocol.
Examples
A default implementation
struct FancyI32 { a: i32 }
impl FancyI32 {
use std::hash::{DefaultHashable, Hasher};
mixin<H: Hasher<H>> DefaultHashable<FancyI32, H>;
}
use std::hash::hash_of;
let x = FancyI32 { a: 1 };
let y = FancyI32 { a: 1 };
let z = FancyI32 { a: 2 };
assert_eq!(x.hash_of(), y.hash_of());
assert_ne!(x.hash_of(), z.hash_of());
Run this example
A custom implementation
struct Foo { a: i32, b: &[u8], extra: u64 }
impl Foo {
use std::hash::Hasher;
fn hash<H: Hasher<H>>(self: &Foo, hasher: &mut H) {
self.a.hash(hasher);
self.b.hash(hasher);
// Skip the `extra`, if two instances of `Foo` are otherwise equal,
// but differ in the value of `extra`, they will hash to the same value.
}
}
use std::hash::hash_of;
let v1 = Foo { a: 1, b: "foo", extra: 0 };
let v2 = Foo { a: 1, b: "foo", extra: 1 };
let v3 = Foo { a: 1, b: "bar", extra: 0 };
assert_eq!(v1.hash_of(), v2.hash_of());
assert_ne!(v1.hash_of(), v3.hash_of());
Run this example
Required methods
-
fn hash(a: &Self, hasher: &mut H)