Generic hashing support.
This module provides a generic way to compute the hash of a value. The simplest way to make a type hashable is to use #[derive(Hash)]
:
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; #[derive(Hash)] struct Person { id: u32, name: String, phone: u64, } let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777, }; let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777, }; assert!(calculate_hash(&person1) != calculate_hash(&person2)); fn calculate_hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() }
If you need more control over how a value is hashed, you need to implement the Hash
trait:
use std::collections::hash_map::DefaultHasher; 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); } } let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777, }; let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777, }; assert_eq!(calculate_hash(&person1), calculate_hash(&person2)); fn calculate_hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() }
Hash |
Derive macro generating an impl of the trait |
BuildHasherDefault |
Used to create a default |
SipHasher |
Deprecated An implementation of SipHash 2-4. |
BuildHasher |
A trait for creating instances of |
Hash |
A hashable type. |
Hasher |
A trait for hashing an arbitrary stream of bytes. |
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/hash/index.html