闭包作为 Rust 结构中的类型

2023-12-22

我正在尝试在 Rust 中创建这样的结构:

pub struct Struct<T, F>
    where T: Eq,
          T: Hash,
          F: Fn() -> T
{
    hashMap: HashMap<T, F>,
    value: T,
}

我的构造函数如下所示:

pub fn new(init_value: T) -> Struct<T, F> {
    Struct {
        hashMap: HashMap::new(),
        value: init_state,
    }
}

但是,当尝试实例化该类时,使用let a = Struct::<MyEnum>::new(MyEnum::Init);,编译器抱怨泛型需要两个参数(expected 2 type arguments, found 1)

I saw here https://doc.rust-lang.org/book/closures.html这段代码有效:

fn call_with_one<F>(some_closure: F) -> i32
    where F: Fn(i32) -> i32 {

    some_closure(1)
}

let answer = call_with_one(|x| x + 2);

我想问题出在我的模板实例化中有另一个泛型,但我该怎么做呢?


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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

闭包作为 Rust 结构中的类型 的相关文章

随机推荐