如何使指针可以清洗?

Wil*_*hes 7 rust

在Rust中,我想将枚举视为相等,但仍然能够通过指针区分不同的实例.这是一个玩具示例:

use self::Piece::*;
use std::collections::HashMap;

#[derive(Eq, PartialEq)]
enum Piece {
    Rook,
    Knight,
}

fn main() {
    let mut positions: HashMap<&Piece, (u8, u8)> = HashMap::new();
    let left_rook = Rook;
    let right_rook = Rook;

    positions.insert(&left_rook, (0, 0));
    positions.insert(&right_rook, (0, 7));
}
Run Code Online (Sandbox Code Playgroud)

然而,编译器要我定义HashPiece:

error[E0277]: the trait bound `Piece: std::hash::Hash` is not satisfied
  --> src/main.rs:11:52
   |
11 |     let mut positions: HashMap<&Piece, (u8, u8)> = HashMap::new();
   |                                                    ^^^^^^^^^^^^ the trait `std::hash::Hash` is not implemented for `Piece`
   |
   = note: required because of the requirements on the impl of `std::hash::Hash` for `&Piece`
   = note: required by `<std::collections::HashMap<K, V>>::new`

error[E0599]: no method named `insert` found for type `std::collections::HashMap<&Piece, (u8, u8)>` in the current scope
  --> src/main.rs:15:15
   |
15 |     positions.insert(&left_rook, (0, 0));
   |               ^^^^^^
   |
   = note: the method `insert` exists but the following trait bounds were not satisfied:
           `&Piece : std::hash::Hash`

error[E0599]: no method named `insert` found for type `std::collections::HashMap<&Piece, (u8, u8)>` in the current scope
  --> src/main.rs:16:15
   |
16 |     positions.insert(&right_rook, (0, 7));
   |               ^^^^^^
   |
   = note: the method `insert` exists but the following trait bounds were not satisfied:
           `&Piece : std::hash::Hash`
Run Code Online (Sandbox Code Playgroud)

我希望在我的枚举上定义Rook相等,以便一个等于另一个.但是,我希望能够区分Rook我的positionshashmap中的不同实例.

我该怎么做呢?我不想定义HashPiece,但已经在指针定义肯定哈希?

She*_*ter 7

Rust中的原始指针(*const T,*mut T)和引用(&T,&mut T)之间存在差异.你有一个参考.

Hash 为引用定义为委托给引用项的哈希值:

impl<T: ?Sized + Hash> Hash for &T {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,它根据您的需要定义为原始指针:

impl<T: ?Sized> Hash for *const T {
    fn hash<H: Hasher>(&self, state: &mut H) {
        if mem::size_of::<Self>() == mem::size_of::<usize>() {
            // Thin pointer
            state.write_usize(*self as *const () as usize);
        } else {
            // Fat pointer
            let (a, b) = unsafe {
                *(self as *const Self as *const (usize, usize))
            };
            state.write_usize(a);
            state.write_usize(b);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效:

let mut positions = HashMap::new();
positions.insert(&left_rook as *const Piece, (0, 0));
positions.insert(&right_rook as *const Piece, (0, 7));
Run Code Online (Sandbox Code Playgroud)

但是,在这里使用引用或原始指针是最好的.

如果使用引用,一旦移动了已插入的值,编译器将阻止您使用hashmap,因为引用将不再有效.

如果你使用原始指针,编译器不会阻止你,但是你会有悬挂指针,这可能导致内存不安全.

在你的情况下,我想我会尝试重新构造代码,以便一个片段在内存地址之外是唯一的.也许只是一些递增的数字:

positions.insert((left_rook, 0), (0, 0));
positions.insert((right_rook, 1), (0, 7));
Run Code Online (Sandbox Code Playgroud)

如果这看起来不可能,你可以随时Box为它提供一个稳定的内存地址.后一种解决方案更类似于Java这样的语言,默认情况下所有内容都是堆分配的.


正如FrancisGagné所说:

我宁愿&'a T在另一个结构中包装一个具有相同标识语义的结构,而*const T不是生命周期被擦除

您可以创建一个处理引用相等性的结构:

#[derive(Debug, Eq)]
struct RefEquality<'a, T>(&'a T);

impl<'a, T> std::hash::Hash for RefEquality<'a, T> {
    fn hash<H>(&self, state: &mut H)
    where
        H: std::hash::Hasher,
    {
        (self.0 as *const T).hash(state)
    }
}

impl<'a, 'b, T> PartialEq<RefEquality<'b, T>> for RefEquality<'a, T> {
    fn eq(&self, other: &RefEquality<'b, T>) -> bool {
        self.0 as *const T == other.0 as *const T
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用:

positions.insert(RefEquality(&left_rook), (0, 0));
positions.insert(RefEquality(&right_rook), (0, 7));
Run Code Online (Sandbox Code Playgroud)

  • 如果你从不取消引用它们,那么原始指针不会导致记忆不安全.但是,这并不意味着保留指向解除分配对象的原始指针是一个好主意:另一个对象可以在与先前释放的对象相同的内存位置分配.我宁愿在另一个结构中包装一个`&'一个T`,它具有与`*const T`相同的标识语义而不是擦除生命周期. (4认同)