std/hash/
mod.rs

1//! Generic hashing support.
2//!
3//! This module provides a generic way to compute the [hash] of a value.
4//! Hashes are most commonly used with [`HashMap`] and [`HashSet`].
5//!
6//! [hash]: https://en.wikipedia.org/wiki/Hash_function
7//! [`HashMap`]: ../../std/collections/struct.HashMap.html
8//! [`HashSet`]: ../../std/collections/struct.HashSet.html
9//!
10//! The simplest way to make a type hashable is to use `#[derive(Hash)]`:
11//!
12//! # Examples
13//!
14//! ```rust
15//! use std::hash::{DefaultHasher, Hash, Hasher};
16//!
17//! #[derive(Hash)]
18//! struct Person {
19//!     id: u32,
20//!     name: String,
21//!     phone: u64,
22//! }
23//!
24//! let person1 = Person {
25//!     id: 5,
26//!     name: "Janet".to_string(),
27//!     phone: 555_666_7777,
28//! };
29//! let person2 = Person {
30//!     id: 5,
31//!     name: "Bob".to_string(),
32//!     phone: 555_666_7777,
33//! };
34//!
35//! assert!(calculate_hash(&person1) != calculate_hash(&person2));
36//!
37//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
38//!     let mut s = DefaultHasher::new();
39//!     t.hash(&mut s);
40//!     s.finish()
41//! }
42//! ```
43//!
44//! If you need more control over how a value is hashed, you need to implement
45//! the [`Hash`] trait:
46//!
47//! ```rust
48//! use std::hash::{DefaultHasher, Hash, Hasher};
49//!
50//! struct Person {
51//!     id: u32,
52//!     # #[allow(dead_code)]
53//!     name: String,
54//!     phone: u64,
55//! }
56//!
57//! impl Hash for Person {
58//!     fn hash<H: Hasher>(&self, state: &mut H) {
59//!         self.id.hash(state);
60//!         self.phone.hash(state);
61//!     }
62//! }
63//!
64//! let person1 = Person {
65//!     id: 5,
66//!     name: "Janet".to_string(),
67//!     phone: 555_666_7777,
68//! };
69//! let person2 = Person {
70//!     id: 5,
71//!     name: "Bob".to_string(),
72//!     phone: 555_666_7777,
73//! };
74//!
75//! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
76//!
77//! fn calculate_hash<T: Hash>(t: &T) -> u64 {
78//!     let mut s = DefaultHasher::new();
79//!     t.hash(&mut s);
80//!     s.finish()
81//! }
82//! ```
83#![stable(feature = "rust1", since = "1.0.0")]
84
85pub(crate) mod random;
86
87#[stable(feature = "rust1", since = "1.0.0")]
88pub use core::hash::*;
89
90#[stable(feature = "std_hash_exports", since = "1.76.0")]
91pub use self::random::{DefaultHasher, RandomState};