如何在闭包内引用self [复制]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

如果我有一个类似的结构

// 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
1个回答
1
投票

你可以将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!()
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.