我正在尝试实现语言词典。我开始尝试解析一个字符串并返回一个字符串向量,但是我在借阅检查器上遇到了麻烦。在尝试了很多关于堆栈溢出的建议后,我真的迷路了。
mod parser {
pub struct Lexer {}
impl Lexer {
pub fn parse<'a>(&self, source: &'a str) -> Vec<&'a str> {
let mut token = String::new();
let mut tokens: Vec<&'a str> = vec![];
for character in source.chars() {
// ' ' is just a test example, a full lexer
// will have more complex logic to split the string
if character == ' ' {
tokens.push(&token); // what do I do here to create a &str with the correct lifetime?
token = String::new();
continue;
}
token.push(character);
}
tokens
}
}
}
fn main() {
let lexer = parser::Lexer {};
let tokens = lexer.parse("some dummy text");
}
error[E0597]: `token` does not live long enough
--> src/main.rs:13:34
|
13 | tokens.push(&token); // what do I do here to create a &str with the correct lifetime?
| ^^^^^ borrowed value does not live long enough
...
22 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the method body at 5:22...
--> src/main.rs:5:22
|
5 | pub fn parse<'a>(&self, source: &'a str) -> Vec<&'a str> {
| ^^
我猜想有一种神奇的方法可以在将字符串推入令牌向量之前以正确的生命周期克隆我的字符串,但是我不确定我实际上已经做过什么。
我正在使用Rust 1.28.0
编辑:
它与标记为重复的答案有点不同,因为我返回的是字符串向量,而不仅仅是&str
。
如果我将方法更改为以下内容:
pub fn parse(&self, source: &str) -> Vec<&str> {
vec!["some", "dummy", "text"]
}
编译器不会抱怨生存期,并且其他答案中也没有解释此行为。在这种情况下,字符串的所有权属于谁?我不能使用动态创建的字符串复制此所有权吗?