【问题标题】:How to reference self inside a closure [duplicate]如何在闭包内引用 self [重复]
【发布时间】:2019-02-14 06:33:27
【问题描述】:

如果我有类似的结构

// 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,但我不确定如何解决它。有解决办法吗?

【问题讨论】:

  • 请提供MCVE 例如通过使用the playground。在此上下文中缺少结构 OtherStruct。尝试将您的示例减少到最低限度,以便问题不言自明。另外请在您的问题中包含错误,这样我们就不必执行代码来查看问题所在。
  • 投掷一个合适的 - 这是无用的夸张。您得到什么具体错误?搜索错误消息是找到问题解决方案的最佳方法之一,但只有当人们包含这些错误时才有效。
  • pub foo: bar[] — 这不是有效的 Rust 代码。你不能编造语法,希望编译器能弄明白。

标签: rust


【解决方案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!()
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多