Rust 将可选的自变异函数作为结构成员的正确方法是什么?

Rust 将可选的自变异函数作为结构成员的正确方法是什么?,rust,Rust,我想这样做: 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);

我想这样做:

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);
        }
    }
}
structfoo{
id:u32,
updater:Option,//这里的Foo应该是self
}
impl-Foo{
fn更新(&mut self){
如果让某些(更新程序)=self.updater{
_更新程序(&mut self);
}
}
}

这里的意图可能吗?分配给
Foo::updater
的语法是什么?

您可以使用函数指针:

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);
}
structfoo{
id:u32,
更新程序:选项,
}
impl-Foo{
fn更新(&mut self){
如果让某些(更新程序)=self.updater{
_更新程序(self);
}
}
}
fn main(){
让mutfoo=foo{id:41,updater:None};
foo.updater=Some(|foo | foo.id+=1);
update();
println!(“foo.id:{}”,foo.id);
}
在这里,不捕获任何内容的闭包隐式转换为函数,然后用作函数指针

另见:


这有什么问题吗?谢谢!抱歉,如果这似乎是一个微不足道的问题-我比我想象的要近。我认为
Fn
vs
Fn
a|foo.updater=Some(| bar:&mut foo{})的语法让我困惑。