Skip to content

Commit 61bb9b2

Browse files
committed
Add more information about implementing Hash
A bit of duplication from the module documentation, but simplified to be closer to being trivially copy-paste-able.
1 parent c41227f commit 61bb9b2

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/libcore/hash/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,33 @@ mod sip;
9797
/// In other words, if two keys are equal, their hashes should also be equal.
9898
/// `HashMap` and `HashSet` both rely on this behavior.
9999
///
100+
/// ## Derivable
101+
///
100102
/// This trait can be used with `#[derive]` if all fields implement `Hash`.
101103
/// When `derive`d, the resulting hash will be the combination of the values
102104
/// from calling `.hash()` on each field.
105+
///
106+
/// ## How can I implement `Hash`?
107+
///
108+
/// If you need more control over how a value is hashed, you need to implement
109+
/// the trait `Hash`:
110+
///
111+
/// ```
112+
/// use std::hash::{Hash, Hasher};
113+
///
114+
/// struct Person {
115+
/// id: u32,
116+
/// name: String,
117+
/// phone: u64,
118+
/// }
119+
///
120+
/// impl Hash for Person {
121+
/// fn hash<H: Hasher>(&self, state: &mut H) {
122+
/// self.id.hash(state);
123+
/// self.phone.hash(state);
124+
/// }
125+
/// }
126+
/// ```
103127
#[stable(feature = "rust1", since = "1.0.0")]
104128
pub trait Hash {
105129
/// Feeds this value into the state given, updating the hasher as necessary.

0 commit comments

Comments
 (0)