Rust 如何在结构上存储回调列表?

Rust 如何在结构上存储回调列表?,rust,Rust,这是对我的问题的后续行动 我试图创建(并在事件循环附近存储)回调函数列表,这些函数将在将来的某个不确定点被调用 struct ComplexThing { calls: Vec<Box<FnMut()>>, } impl ComplexThing { fn call<'a, T: FnMut() + 'a>(&'a mut self, func: T) { self.calls.push(Box::new(func)

这是对我的问题的后续行动

我试图创建(并在事件循环附近存储)回调函数列表,这些函数将在将来的某个不确定点被调用

struct ComplexThing {
    calls: Vec<Box<FnMut()>>,
}


impl ComplexThing {
    fn call<'a, T: FnMut() + 'a>(&'a mut self, func: T) {
        self.calls.push(Box::new(func));
    }
}
我尝试将其添加到
结构
,该结构修复了调用
推送
时有关生存时间的错误

struct ComplexThing<'a> {
    calls: Vec<Box<FnMut() + 'a>>,
}


impl ComplexThing {
    fn call<'a, T: FnMut() + 'a>(&'a mut self, func: T) {
        self.calls.push(Box::new(func));
    }
}

是的,我假设结构在
ComplexThing
上有一个
'a
是一个泛型生存期参数,需要像泛型类型参数一样定义它。如果您有一个
struct Foo
,您将无法编写
impl Foo
,因为范围中没有具体的类型
T
;如果希望它是泛型的,则需要定义它,
impl-Foo
。这也允许您编写约束,例如
impl-Foo
来实现
Foo
上的方法,仅当
T
是实现
Clone
的类型时

因此,答案很简单,您需要将生存期
'a
定义为泛型:

impl{…}
盒子
盒子的糖
struct ComplexThing<'a> {
    calls: Vec<Box<FnMut() + 'a>>,
}


impl ComplexThing {
    fn call<'a, T: FnMut() + 'a>(&'a mut self, func: T) {
        self.calls.push(Box::new(func));
    }
}
calls.rs:28:6: 28:18 error: wrong number of lifetime parameters: expected 1, found 0 [E0107]
calls.rs:28 impl ComplexThing {
                 ^~~~~~~~~~~~
impl ComplexThing<'a> {
calls.rs:28:19: 28:21 error: use of undeclared lifetime name `'a` [E0261]
calls.rs:28 impl ComplexThing<'a> {