[英]How to do `Hash` to a unit struct in rust?
我想實現一種可以唯一標識的東西 ,此外,它不包含其他字段。 BasicObject
像ruby中的BasicObject
或java中的Object
。
我添加了PartialEq
特性。
struct Thing;
impl PartialEq for Thing {
fn eq(&self, other: &Thing) -> bool {
unsafe {
self as *const Thing == other as *const Thing
}
}
}
現在,我想允許它可以進行哈希處理,問題是如何為沒有字段的單元結構實現哈希特性? 還是應該在其中添加某種object_id
?
您不能依靠指針地址來確定Rust中單元結構的唯一性,例如,以下代碼將打印兩次相同的地址:
struct Foo;
fn main() {
let x = Foo;
let y = Foo;
println!("{}", &x as *const _);
println!("{}", &y as *const _);
}
您需要讓它們至少占用一個內存字節,例如,給它們一個從未使用過的字段:
struct Thing {
x: u8;
}
impl Thing {
fn new() -> Thing {
Thing { x: 0u8 }
}
}
然后,一種簡單的方法是繼續沿原樣運行,並使用內存中對象的地址作為Hash的基值:
use std::hash::{hash,Hash};
use std::hash::sip::SipState;
struct Thing;
impl Hash for Thing {
fn hash(&self, state: &mut SipState) {
let addr = self as *const Thing as u64;
addr.hash(state);
}
}
fn main() {
let f = Thing;
println!("{}", hash(&f));
}
注意:將&Thing
為*const Thing
(然后轉換為u64
)並非不安全,因此在PartialEq的實現中不需要unsafe{}
塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.