[英]How can I accept a Rust HashMap with any hashing algorithm?
I'm working on a library that has a function that I would like to be able to accept a HashMap of any hashing algorithm.我正在开发一个具有 function 的库,我希望能够接受任何散列算法的 HashMap。 But when I try to call it with a particular type of HashMap, such as a FnvHashMap, the compiler complains.
但是,当我尝试使用特定类型的 HashMap(例如 FnvHashMap)调用它时,编译器会抱怨。
pub fn func(map: HashMap<u32, u32>) {}
let map: FnvHashMap<u32, u32> = FnvHashMap::default();
func(map);
error[E0308]: mismatched types
--> lib.rs:42:10
|
42 | func(map);
| ^^^ expected struct `RandomState`, found struct `BuildHasherDefault`
|
= note: expected struct `HashMap<_, _, RandomState>`
found struct `HashMap<_, _, BuildHasherDefault<FnvHasher>>`
As FnvHashMap is only a type alias I thought this wouldn't be a problem.由于FnvHashMap只是一个类型别名,我认为这不是问题。
I'm sure there's a way to do this, but I haven't found it yet.我确定有办法做到这一点,但我还没有找到它。 What's the correct way?
正确的方法是什么?
The definition of HashMap
in the docs is: HashMap
在文档中的定义是:
pub struct HashMap<K, V, S = RandomState> { /* fields omitted */ }
RandomState
is the default type, but it can be overridden with another type, including a generic. RandomState
是默认类型,但它可以被其他类型覆盖,包括泛型。 It may not be immediately clear, but most of the HashMap
methods are declared in an impl
block that constraints S: BuildHasher
, which is the trait you need to bound it by:可能不是很清楚,但是大多数
HashMap
方法都在一个约束S: BuildHasher
的impl
块中声明,这是您需要通过以下方式约束它的特征:
use std::hash::BuildHasher;
pub fn func<S: BuildHasher>(map: HashMap<u32, u32, S>) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.