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

时间:2018-01-22 15:04:39

标签: 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);
        }
    }
}

这里的意图是否可行?分配给Foo::updater的语法是什么样的?

1 个答案:

答案 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);
}

这里,一个不捕获任何东西的闭包被隐式转换为一个函数,然后用作函数指针。

另见: