我正在实现代码解析器。我有一个带有Parser
字段的code
结构,这是原始代码的拥有的字符串。我想拆分行并删除空格/注释,并将其存储在借来的字段lines
中。
pub struct Parser<'a> {
code: String,
lines: Vec<&'a str>,
}
impl<'a> Parser<'a> {
pub fn new(code: String) -> Parser<'a> {
let lines = code.split("\n").collect();
Parser { code, lines }
}
}
由于code
拥有,因此它应该活得足够长,以便lines
被引用,因为它们是同一结构的一部分。但是,我得到此错误:
error[E0597]: `code` does not live long enough
--> src/lib.rs:8:21
|
8 | let lines = code.split("\n").collect();
| ^^^^ borrowed value does not live long enough
9 | Parser { code, lines }
10 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 6:6...
--> src/lib.rs:6:6
|
6 | impl<'a> Parser<'a> {
| ^^
如何告诉Rust code
寿命足够长,以便我的程序可以编译?