Trait std::hash::Hash

1.0.0 · source ·
pub trait Hash {
    // Required method
    fn hash<H>(&self, state: &mut H)
       where H: Hasher;

    // Provided method
    fn hash_slice<H>(data: &[Self], state: &mut H)
       where H: Hasher,
             Self: Sized { ... }
}
Expand description

可散列的类型。

实现 Hash 的类型可以通过 Hasher 的实例进行 hash 化。

实现 Hash

如果所有字段都要实现 Hash,则可以用 #[derive(Hash)] 派生 Hash。 产生的哈希将是在每个字段上调用 hash 的值的组合。

#[derive(Hash)]
struct Rustacean {
    name: String,
    country: String,
}
Run

如果您需要更多地控制值的散列方式,则当然可以自己实现 Hash trait:

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);
    }
}
Run

HashEq

同时实现 HashEq 时,保持以下属性很重要:

k1 == k2 -> hash(k1) == hash(k2)

换句话说,如果两个键相等,则它们的哈希也必须相等。 HashMapHashSet 都依赖于这种行为。

值得庆幸的是,在使用 #[derive(PartialEq, Eq, Hash)] 派生 EqHash 时,您不必担心维护此属性。

前缀冲突

hash 的实现应该确保它们传递给 Hasher 的数据是无前缀的。 也就是说,不相等的值应该导致写入两个不同的值序列,并且这两个序列中的任何一个都不应该是另一个序列的前缀。

例如,Hash for &str 的标准实现将额外的 0xFF 字节传递给 Hasher,以便值 ("ab", "c")("a", "bc") 哈希不同。

Portability

由于字节序和类型大小的差异,由 Hash 提供给 Hasher 的数据不应被视为跨平台可移植的。 此外,大多数标准库类型传递的数据在不同的编译器版本之间不应该被认为是稳定的。

这意味着测试不应探测硬编码的哈希值或提供给 Hasher 的数据,而应检查与 Eq 的一致性。

旨在在平台或编译器版本之间可移植的序列化格式应避免编码哈希或仅依赖提供额外保证的 HashHasher 实现。

Required Methods§

source

fn hash<H>(&self, state: &mut H)where H: Hasher,

将该值输入给定的 Hasher

Examples
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

let mut hasher = DefaultHasher::new();
7920.hash(&mut hasher);
println!("Hash is {:x}!", hasher.finish());
Run

Provided Methods§

1.3.0 · source

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

将这种类型的切片送入给定的 Hasher 中。

此方法是为了方便起见,但它的实现也明确未指定。 它不能保证等同于 hash 的重复调用,并且 Hash 的实现应该记住这一点,如果在 PartialEq 实现中没有将 6 视为整个单元,则调用 hash 本身。

例如,一个 VecDeque 实现可能天真地调用 as_slices 然后 hash_slice 对每个调用 hash_slice,但这是错误的,因为两个切片可以随调用更改为 make_contiguous 而不会影响 PartialEq 结果。

由于这些切片不被视为单一单元,而是更大双端队列的一部分,因此无法使用此方法。

Examples
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

let mut hasher = DefaultHasher::new();
let numbers = [6, 28, 496, 8128];
Hash::hash_slice(&numbers, &mut hasher);
println!("Hash is {:x}!", hasher.finish());
Run

Implementors§

source§

impl Hash for AsciiChar

source§

impl Hash for std::cmp::Ordering

1.44.0 · source§

impl Hash for Infallible

source§

impl Hash for ErrorKind

1.7.0 · source§

impl Hash for IpAddr

source§

impl Hash for Ipv6MulticastScope

source§

impl Hash for SocketAddr

source§

impl Hash for Which

source§

impl Hash for std::sync::atomic::Ordering

source§

impl Hash for bool

source§

impl Hash for char

source§

impl Hash for i8

source§

impl Hash for i16

source§

impl Hash for i32

source§

impl Hash for i64

source§

impl Hash for i128

source§

impl Hash for isize

1.29.0 · source§

impl Hash for !

source§

impl Hash for str

source§

impl Hash for u8

source§

impl Hash for u16

source§

impl Hash for u32

source§

impl Hash for u64

source§

impl Hash for u128

source§

impl Hash for ()

source§

impl Hash for usize

1.28.0 · source§

impl Hash for Layout

source§

impl Hash for TypeId

1.64.0 · source§

impl Hash for CStr

1.64.0 · source§

impl Hash for CString

source§

impl Hash for OsStr

source§

impl Hash for OsString

source§

impl Hash for Error

1.1.0 · source§

impl Hash for FileType

1.33.0 · source§

impl Hash for PhantomPinned

source§

impl Hash for Ipv4Addr

source§

impl Hash for Ipv6Addr

source§

impl Hash for SocketAddrV4

source§

impl Hash for SocketAddrV6

1.34.0 · source§

impl Hash for NonZeroI8

1.34.0 · source§

impl Hash for NonZeroI16

1.34.0 · source§

impl Hash for NonZeroI32

1.34.0 · source§

impl Hash for NonZeroI64

1.34.0 · source§

impl Hash for NonZeroI128

1.34.0 · source§

impl Hash for NonZeroIsize

1.28.0 · source§

impl Hash for NonZeroU8

1.28.0 · source§

impl Hash for NonZeroU16

1.28.0 · source§

impl Hash for NonZeroU32

1.28.0 · source§

impl Hash for NonZeroU64

1.28.0 · source§

impl Hash for NonZeroU128

1.28.0 · source§

impl Hash for NonZeroUsize

source§

impl Hash for RangeFull

source§

impl Hash for UCred

Available on Unix only.
source§

impl Hash for Path

source§

impl Hash for PathBuf

source§

impl Hash for PrefixComponent<'_>

source§

impl Hash for Alignment

source§

impl Hash for String

1.19.0 · source§

impl Hash for ThreadId

1.3.0 · source§

impl Hash for Duration

1.8.0 · source§

impl Hash for Instant

1.8.0 · source§

impl Hash for SystemTime

source§

impl<'a> Hash for Component<'a>

source§

impl<'a> Hash for Prefix<'a>

1.10.0 · source§

impl<'a> Hash for Location<'a>

source§

impl<B> Hash for Cow<'_, B>where B: Hash + ToOwned + ?Sized,

1.55.0 · source§

impl<B, C> Hash for ControlFlow<B, C>where B: Hash, C: Hash,

source§

impl<Dyn> Hash for DynMetadata<Dyn>where Dyn: ?Sized,

1.4.0 · source§

impl<F> Hash for Fwhere F: FnPtr,

source§

impl<Idx> Hash for Range<Idx>where Idx: Hash,

source§

impl<Idx> Hash for RangeFrom<Idx>where Idx: Hash,

1.26.0 · source§

impl<Idx> Hash for RangeInclusive<Idx>where Idx: Hash,

source§

impl<Idx> Hash for RangeTo<Idx>where Idx: Hash,

1.26.0 · source§

impl<Idx> Hash for RangeToInclusive<Idx>where Idx: Hash,

source§

impl<K, V, A> Hash for BTreeMap<K, V, A>where K: Hash, V: Hash, A: Allocator + Clone,

1.41.0 · source§

impl<P> Hash for Pin<P>where P: Deref, <P as Deref>::Target: Hash,

1.17.0 · source§

impl<T> Hash for Bound<T>where T: Hash,

source§

impl<T> Hash for Option<T>where T: Hash,

1.36.0 · source§

impl<T> Hash for Poll<T>where T: Hash,

source§

impl<T> Hash for *const Twhere T: ?Sized,

source§

impl<T> Hash for *mut Twhere T: ?Sized,

source§

impl<T> Hash for &Twhere T: Hash + ?Sized,

source§

impl<T> Hash for &mut Twhere T: Hash + ?Sized,

source§

impl<T> Hash for [T]where T: Hash,

source§

impl<T> Hash for (T₁, T₂, …, Tₙ)where T: Hash + ?Sized,

This trait is implemented for tuples up to twelve items long.

1.19.0 · source§

impl<T> Hash for Reverse<T>where T: Hash,

source§

impl<T> Hash for PhantomData<T>where T: ?Sized,

1.21.0 · source§

impl<T> Hash for Discriminant<T>

1.20.0 · source§

impl<T> Hash for ManuallyDrop<T>where T: Hash + ?Sized,

source§

impl<T> Hash for Saturating<T>where T: Hash,

source§

impl<T> Hash for Wrapping<T>where T: Hash,

1.25.0 · source§

impl<T> Hash for NonNull<T>where T: ?Sized,

source§

impl<T> Hash for Rc<T>where T: Hash + ?Sized,

source§

impl<T> Hash for Arc<T>where T: Hash + ?Sized,

source§

impl<T, A> Hash for Box<T, A>where T: Hash + ?Sized, A: Allocator,

source§

impl<T, A> Hash for BTreeSet<T, A>where T: Hash, A: Allocator + Clone,

source§

impl<T, A> Hash for LinkedList<T, A>where T: Hash, A: Allocator,

source§

impl<T, A> Hash for VecDeque<T, A>where T: Hash, A: Allocator,

source§

impl<T, A> Hash for Vec<T, A>where T: Hash, A: Allocator,

根据 core::borrow::Borrow 实现的要求,vector 的哈希值与相应的 3 的哈希值相同。

use std::hash::BuildHasher;

let b = std::collections::hash_map::RandomState::new();
let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(v), b.hash_one(s));
Run
source§

impl<T, E> Hash for Result<T, E>where T: Hash, E: Hash,

source§

impl<T, const N: usize> Hash for [T; N]where T: Hash,

数组的哈希值与对应的 X 像素的哈希值相同,符合实现的要求。

use std::hash::BuildHasher;

let b = std::collections::hash_map::RandomState::new();
let a: [u8; 3] = [0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(a), b.hash_one(s));
Run
source§

impl<T, const N: usize> Hash for Simd<T, N>where LaneCount<N>: SupportedLaneCount, T: SimdElement + Hash,

source§

impl<Y, R> Hash for GeneratorState<Y, R>where Y: Hash, R: Hash,