首页 > 解决方案 > 如何在闭包中引用 self

问题描述

如果我有一个像

// In app.rs
pub struct App {
    pub foo: bar[],
    pub bar_index: i32,
    pub true_false: bool
}

impl App {
    pub fn access<F: Fn(&mut OtherStruct)> (&mut self, action: F) {
        if let OtherStruct(baz) = &mut self.foo[self.bar_index] {
            action(baz);
        }
    }
}

// In main.rs
// `app` is a mutable variable defined elsewhere
app.access(|baz| {
    if app.true_false {
        // do something
    });

运行这个app.access会导致借用检查器抛出一个合适的结果。我认为这是因为我app在闭包中引用,但我不确定如何修复它。有针对这个的解决方法吗?

标签: rust

解决方案


您可以作为参数self传入:action

impl App {
    pub fn access<F: Fn(&App, &mut OtherStruct)>(&mut self, action: F) {
        if let OtherStruct(baz) = &mut self.foo[self.bar_index] {
            action(&self, baz);
        }
    }
}
app.access(|app, baz| {
    if app.true_false {
        unimplemented!()
    }
});

推荐阅读