【发布时间】:2015-08-19 23:56:23
【问题描述】:
考虑以下代码:
use std::collections::HashMap;
type KeyCode = char;
type CmdType = Fn(&mut E);
struct E {
key_map: HashMap<KeyCode, Box<CmdType>>,
}
impl E {
fn map_key(&mut self, key: KeyCode, function: Box<CmdType>) {
self.key_map.insert(key, function);
}
fn quit(&mut self) { println!("quitting"); /* ... */ }
}
fn main() {
let mut e = E { key_map: HashMap::new() };
e.map_key('q', Box::new(|e: &mut E| e.quit()));
match e.key_map.get(&'q') {
Some(f) => f(&mut e),
None => {}
}
}
其中doesn't compile 因为我试图将e 传递给f:
不能将
e借用为可变的,因为e.key_map也借用为不可变的
但是当e.key_map 的借用结束时,我将无法再访问f。那么我该如何准确地调用地图内的闭包呢?
【问题讨论】:
标签: compiler-errors rust borrow-checker