rust - 如何在闭包中引用 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
在闭包中引用,但我不确定如何修复它。有针对这个的解决方法吗?
解决方案
您可以作为参数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!()
}
});
推荐阅读
- google-apps-script - 使用 Apps 脚本为 GDocs 中的行或表格单元格添加边框
- mysql - Hibernate 和 EclipseLink 兼容的 TableGenerator 配置
- elasticsearch - 为什么在 elasticsearch 的全文搜索中,更精确的匹配比不太精确的匹配得分低?
- python - 从包含特定字符串的数据框中删除行
- solr - 在 solr 中仅索引来自 HTML 的纯文本
- php - 如何在yii2中添加最小计算
- android - 当应用程序在android后台时如何从推送通知中接收自定义数据
- spring - 如何为生产设置 Corda 节点?
- powershell - powershell日期比较需要删除文件
- html - justify-content 和 align-items 在使用显示时无法正常工作:flex