我正在尝试对结构进行 Sha256
哈希处理,以根据其内容为该结构生成 GUID。
use sha2::{Digest, Sha256};
use std::hash::{Hash, Hasher};
#[derive(Hash)]
struct Person {
firstName: String;
lastName: String;
}
let a = Person {
firstName: "bob".to_string(),
lastName: "the builder".to_string()
}
let mut s = Sha256::new();
a.hash(&mut s);
println!("{}", s.finsih());
我的扩展目标是简单地使用 a.id()
来散列该结构上的所有属性。这是一个 impl Person { id() -> String }
吗?
我试过使用 impl x for y
但抛出一个 impl doesn't use types inside crate
impl Hasher for Sha256 {
fn finish(&self) -> u64 {
self.0.result()
}
fn write(&mut self, msg: &[u8]) {
self.0.input(msg)
}
}
最佳答案
You can't implement an external trait for an external type .
你的问题是 digest
类型,比如 Sha256
,没有实现 Hasher
- 因为它们是不同种类的哈希。 Hasher
特征适用于散列数据 into a 64 bit hash value 的类型, 用于 Rust 自己的代码,如 HashMap
。另一方面,Sha256
给出了 32 字节的散列。
要使用 Sha256
,您需要手动将要计算其哈希值的字节输入它 - 您可以在 impl
block 中执行此操作。
impl Person {
fn id(&self) -> sha2::digest::generic_array::GenericArray<u8, <Sha256 as Digest>::OutputSize> {
let mut s = Sha256::new();
s.input(self.firstName.as_bytes());
s.input(self.lastName.as_bytes());
s.result()
}
}
关于hash - 如何使用实现 sha2 crate 中的 Digest 特征的类型(例如 Sha256)对结构进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56197060/