无法引用 &str 的一部分,因为它的寿命不够长,即使它引用的内容确实如此



我正在Rust中实现一个扫描仪。我在Scanner结构上有一个scan方法,它以字符串切片作为源代码,将该字符串分解为UTF-8字符的Vec<&str>(使用板条箱unicode_segmentation(,然后将每个字符委托给scan_token方法,该方法确定其词法标记并返回它。

extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
struct Scanner {
start: usize,
current: usize,
}
#[derive(Debug)]
struct Token<'src> {
lexeme: &'src [&'src str],
}
impl Scanner {
pub fn scan<'src>(&mut self, source: &'src str) -> Vec<Token<'src>> {
let mut offset = 0;
let mut tokens = Vec::new();
// break up the code into UTF8 graphemes
let chars: Vec<&str> = source.graphemes(true).collect();
while let Some(_) = chars.get(offset) {
// determine which token this grapheme represents
let token = self.scan_token(&chars);
// push it to the tokens array
tokens.push(token);
offset += 1;
}
tokens
}
pub fn scan_token<'src>(&mut self, chars: &'src [&'src str]) -> Token<'src> {
// get this lexeme as some slice of the slice of chars
let lexeme = &chars[self.start..self.current];
let token = Token { lexeme };
token
}
}
fn main() {
let mut scanner = Scanner {
start: 0,
current: 0,
};
let tokens = scanner.scan("abcd");
println!("{:?}", tokens);
}

我收到的错误是:

error[E0597]: `chars` does not live long enough
--> src/main.rs:22:42
|
22 |             let token = self.scan_token(&chars);
|                                          ^^^^^ borrowed value does not live long enough
...
28 |     }
|     - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'src as defined on the method body at 15:17...
--> src/main.rs:15:17
|
15 |     pub fn scan<'src>(&mut self, source: &'src str) -> Vec<Token<'src>> {
|                 ^^^^

我想我理解为什么这不起作用背后的逻辑:这个错误清楚地表明,chars的寿命需要与'src的寿命一样长,因为tokens包含对chars内部数据的切片引用。

我不明白的是,既然chars只是一个对象的引用片段,而的生命周期为'src(即source(,为什么tokenschars被丢弃后不能引用这些数据?我对低级编程还相当陌生,我想我关于引用+生存期的直觉可能有些崩溃。

您的问题可以简化为:

pub fn scan<'a>(source: &'a str) -> Option<&'a str> {
let chars: Vec<&str> = source.split("").collect();
scan_token(&chars)
}
pub fn scan_token<'a>(chars: &'a [&'a str]) -> Option<&'a str> {
chars.last().cloned()
}
error[E0597]: `chars` does not live long enough
--> src/lib.rs:3:17
|
3 |     scan_token(&chars)
|                 ^^^^^ borrowed value does not live long enough
4 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 1:13...
--> src/lib.rs:1:13
|
1 | pub fn scan<'a>(source: &'a str) -> Option<&'a str> {
|             ^^

scan_token函数要求对切片的引用和切片内部的引用具有相同的生存期:&'a [&'a str]。由于Vec的寿命较短,因此统一寿命必须是这样的。然而,向量的寿命不足以返回值。

删除不需要的生存期:

pub fn scan_token<'a>(chars: &[&'a str]) -> Option<&'a str>

将这些更改应用于完整的代码,您可以看到核心问题在Token:的定义中重复出现

struct Token<'src> {
lexeme: &'src [&'src str],
}

这种构造使得代码绝对不可能按原样编译——没有一个切片向量的寿命与切片一样长。你的代码在这种形式下根本不可能。

可以传入一个对Vec的可变引用以用作存储,但这将是非常不寻常的,并且在尝试做更大的事情时会遇到很多缺点:

impl Scanner {
pub fn scan<'src>(&mut self, source: &'src str, chars: &'src mut Vec<&'src str>) -> Vec<Token<'src>> {
// ...
chars.extend(source.graphemes(true));
// ...
while let Some(_) = chars.get(offset) {
// ...
let token = self.scan_token(chars);
// ...
}
// ...
}
// ...    
}
fn main() {
// ...
let mut chars = Vec::new();
let tokens = scanner.scan("abcd", &mut chars);
// ...
}

你可能只是想让Token成为Vec<&'src str>

另请参阅:

  • 在一个代码中不能一次借用一次以上的可变代码,但在另一个非常相似的代码中可以
  • 有什么方法可以返回对函数中创建的变量的引用吗

最新更新