I'm trying to implement a language lexer. I began trying to parse a string and return a vector of strings but I'm stumbling upon the borrow checker. After trying lots of things suggested here on Stack Overflow I'm really lost.
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> {
| ^^
I guess there's some magical method that will clone my string with the correct lifetime before I push it to my tokens vector, but I'm not sure about anything I've done actually.
I'm using Rust 1.28.0
Edit:
It's a bit different from the answer marked as duplicate because I'm returning a vector of strings, not simply a &str
.
If I change my method to the following:
pub fn parse(&self, source: &str) -> Vec<&str> {
vec!["some", "dummy", "text"]
}
The compiler doesn't complain about lifetimes and this behavior is not explained in the other answers. In this case, the ownership of the strings belongs to whom? Can I not replicate this ownership with dynamically created strings?