I\'m new to Rust and I\'m having some trouble with the borrow checker. I don\'t understand why this code won\'t compile. Sorry if this is close to a previously answered ques
The problem is that you're allocating a new String
(token_string
) inside the lex
function and then returning an array of references to it, but token_string
will get dropped (and the memory freed) as soon as it falls out of scope at the end of the function.
fn lex(s: &String) -> Vec<&str> {
let token_string: String = s.replace("(", " ( ") // <-- new String allocated
.replace(")", " ) ");
let token_list: Vec<&str> = token_string.split_whitespace()
.collect();
token_list // <-- this is just an array of wide pointers into token_string
} // <-- token_string gets freed here, so the returned pointers
// would be pointing to memory that's already been dropped!
There's a couple of ways to address this. One would be to force the caller of lex
to pass in the buffer that you want to use to collect into. This would change the signature to fn lex<'a>(input: &String, buffer: &'a mut String) -> Vec<&'a str>
This signature would specify that the lifetimes of the returned &str
s will be at least as long as the lifetime of the buffer that's passed in.
Another way would be to just return a Vec
instead of Vec<&str>
if you can tolerate the extra allocations.