如果我有类似的结构
// 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
,但不确定如何解决它。有解决办法吗?
答案 0 :(得分: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!()
}
});