我想这样做:
struct Foo {
id: u32,
updater: Option<Fn(&mut Foo)>, // the Foo here should be self
}
impl Foo {
fn update(&mut self) {
if let Some(the_updater) = self.updater {
the_updater(&mut self);
}
}
}
这里的意图是否可行?分配给Foo::updater
的语法是什么样的?
答案 0 :(得分:1)
您可以使用函数指针:
struct Foo {
id: u32,
updater: Option<fn(&mut Foo)>,
}
impl Foo {
fn update(&mut self) {
if let Some(the_updater) = self.updater {
the_updater(self);
}
}
}
fn main() {
let mut foo = Foo { id: 41, updater: None };
foo.updater = Some(|foo| foo.id += 1);
foo.update();
println!("foo.id: {}", foo.id);
}
这里,一个不捕获任何东西的闭包被隐式转换为一个函数,然后用作函数指针。
另见: