【发布时间】:2021-12-31 08:25:24
【问题描述】:
我正在尝试使用 rust 编写自己的编程语言,并且大多数功能都已完成,所以我认为我可以在 UnknownIdentifier 错误中添加能够找到与用户想要的任何内容最接近的匹配项的能力
然而,在我找到最接近的匹配之前,我发现克隆 HashMap
ErrorGenerator::error 函数:
#[allow(non_snake_case)]
mod ErrorGenerator {
pub fn error(name: &str, explanation: &str, line: usize, col: usize, file: String, after_f: Box<dyn Fn() -> ()>) -> ! {
eprintln!("\n[ERROR] {}, Line {:?}, Column {:?}", file, line, col);
eprintln!(" {}: {}", name, explanation);
after_f();
exit(1);
}
}
ErrorGenerator::error(
"UnknownIdentifier",
&format!("unknown identifier: `{}`, this identifier could not be found", tokenc.repr()),
tokenc.line,
tokenc.col,
tokenc.file,
Box::new(||{
let mut hashc: Vec<String> = hashs.clone().into_keys().collect();
hashc.sort();
}),
);
这是它给出的错误:
error[E0597]: `hashs` does not live long enough
--> src/runtime/runtime.rs:960:70
|
959 | Box::new(||{
| - -- value captured here
| _____________________________________|
| |
960 | | let mut hashc: Vec<String> = hashs.clone().into_keys().collect();
| | ^^^^^ borrowed value does not live long enough
961 | | hashc.sort();
962 | | }),
| |______________________________________- cast requires that `hashs` is borrowed for `'static`
...
1203 | }
| - `hashs` dropped here while still borrowed
问题的解决方案可能是:
- 一种在“静态生命周期”中将方法中创建的可变变量借入闭包的方法 或
- 一种克隆 HashMap
而不将其移动到闭包中的方法
你可以在https://github.com/kaiserthe13th/tr-lang/tree/unknown-id-err-impl找到完整的代码
【问题讨论】:
标签: rust hashmap closures borrow-checker cloning