Struct::new
没有任何依赖的参数F
,所以编译器无法推断它应该使用什么类型F
。如果您稍后调用使用的方法F
,然后编译器将使用该信息来计算出Struct
的具体类型。例如:
use std::hash::Hash;
use std::collections::HashMap;
pub struct Struct<T, F>
where T: Eq,
T: Hash,
F: Fn() -> T,
{
hash_map: HashMap<T, F>,
value: T,
}
impl<T, F> Struct<T, F>
where T: Eq,
T: Hash,
F: Fn() -> T,
{
pub fn new(init_value: T) -> Struct<T, F> {
Struct {
hash_map: HashMap::new(),
value: init_value,
}
}
pub fn set_fn(&mut self, value: T, func: F) {
self.hash_map.insert(value, func);
}
}
fn main() {
let mut a = Struct::new(0);
a.set_fn(0, || 1); // the closure here provides the type for `F`
}
但这有一个问题。如果我们打电话set_fn
第二次使用不同的闭包:
fn main() {
let mut a = Struct::new(0);
a.set_fn(0, || 1);
a.set_fn(1, || 2);
}
然后我们得到一个编译器错误:
error[E0308]: mismatched types
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^ expected closure, found a different closure
|
= note: expected type `[closure@<anon>:32:17: 32:21]`
= note: found type `[closure@<anon>:33:17: 33:21]`
note: no two closures, even if identical, have the same type
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^
help: consider boxing your closure and/or using it as a trait object
--> <anon>:33:17
|
33 | a.set_fn(1, || 2);
| ^^^^
正如编译器所提到的,每个闭包表达式都定义了一个全新的类型并计算为该类型。然而,通过定义Struct
就像你所做的那样,你正在强制执行中的所有功能HashMap
具有相同的类型。这真的是你想要的吗?
如果你想映射不同的值T
对于可能不同类型的闭包,那么您需要按照编译器的建议使用特征对象而不是泛型。如果您希望结构拥有闭包,那么您必须使用Box
围绕对象类型。
pub struct Struct<T>
where T: Eq,
T: Hash,
{
hash_map: HashMap<T, Box<Fn() -> T + 'static>>,
value: T,
}
set_fn
那么可能看起来像这样:
pub fn set_fn<F: Fn() -> T + 'static>(&mut self, value: T, func: F) {
self.hash_map.insert(value, Box::new(func));
}