Why does the borrow checker think that content does not live long enough?

Viewed 139

I am still pretty new to Rust and I have this function:

Edit: Here is a newer version of the function with the same issue as far as I can tell

pub fn new_from_file_path(path: &str) -> Parser {
    let path_buf: PathBuf = PathBuf::from(path);
    let absolute_path: PathBuf = std::fs::canonicalize(path_buf).unwrap();
    let data: String = std::fs::read_to_string(absolute_path).unwrap();
    let clone = data.clone();

    let s_slice: &str = &clone[..];
    return Parser::new_from_string_data(s_slice);
}

Here is the implementation of the new_from_string_data() function

pub fn new_from_string_data(data: &str) -> Parser {
    let parser = Parser::new(data.chars());
    return parser;
}

This is the struct definition for parser :

pub struct Parser<'a> {
    tokenizer: Tokenizer<'a>,
}

Here is a screenshot of the error message I am getting

A screenshot of the error message Any help would be greatly appreciated, please also let me know if more information is needed.

2 Answers

new_from_string_data function returns a Parser with the same lifetime as it's input argument data.

In the case of new_from_file_path, data is s_slice which is a slice of the string clone owned by the function new_from_file_path. Hence the returned Parser would reference clone which is destroyed when returning from the function new_from_file_path

str::chars() returns an iterator struct that requires an explicit lifetime as it (presumably, I haven't read the full struct definition myself) references the data passed to chars() (pub struct Chars<'a> { /* fields omitted */ }), just like your Parser struct, and you are generating the referenced variable(s) inside of new_from_file_path in the statement let clone = data.clone();.

I'd suggest simply adding a lifetime annotation to the function header so it reads as follows:

pub fn new_from_file_path<'a>(path: &'a str) -> Parser<'a> {...}

This wont complicate calling the function and tells the compiler that the returned Parser struct and its refrences should have the same lifetime as the data passed to the function.

Related