]> git.lizzy.rs Git - rust.git/commitdiff
Add more information about implementing `Hash`
authorCarol (Nichols || Goulding) <carol.nichols@gmail.com>
Sun, 22 May 2016 22:29:13 +0000 (18:29 -0400)
committerCarol (Nichols || Goulding) <carol.nichols@gmail.com>
Mon, 23 May 2016 14:03:44 +0000 (10:03 -0400)
A bit of duplication from the module documentation, but simplified
to be closer to being trivially copy-paste-able.

src/libcore/hash/mod.rs

index 7f0d7517a57c034ab3f9406387e7d94f606086cc..844a24e80d1a798902b5e762d4c87e211b0c647b 100644 (file)
 /// In other words, if two keys are equal, their hashes should also be equal.
 /// `HashMap` and `HashSet` both rely on this behavior.
 ///
+/// ## Derivable
+///
 /// This trait can be used with `#[derive]` if all fields implement `Hash`.
 /// When `derive`d, the resulting hash will be the combination of the values
 /// from calling `.hash()` on each field.
+///
+/// ## How can I implement `Hash`?
+///
+/// If you need more control over how a value is hashed, you need to implement
+/// the trait `Hash`:
+///
+/// ```
+/// 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);
+///     }
+/// }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub trait Hash {
     /// Feeds this value into the state given, updating the hasher as necessary.