New to Rust...Getting an error. Pls help

Hello Team,
This is my program - just gets user input until End is typed and the strings get stored in a vector. Sounds simple but I am struggling with it :upside_down_face:
Please help.


pub fn persist_strings()
// vairable declarations.

let mut line_input = Vec::new();


    println!("Your input please :");
    let mut buffer = String::new();
    match stdin().read_line(&mut buffer)
        Ok(_) => { 
            let parsed = buffer.trim_end();
            if parsed == "End"
            else {
        Err(_) => println!("An error has occured."),


Error -
error[E0597]: buffer does not live long enough
--> src/
43 | let parsed = buffer.trim_end();
| ^^^^^^ borrowed value does not live long enough

Hi and welcome, please read the following post on syntax highlighting and code blocks

Your program uses a buffer in each loop iteration that contains a line. The .trim_end() call creates a slice of that same buffer. This slice references / points into buffer and can’t be used anymore once buffer is dropped at the end of each loop iteration, hence it can’t be stored in line_input because line_input lives longer, throughout the whole loop over all the lines. A possible fix would be to give line_input the type Vec<String> (currently it’s Vec<&str>) by pushing an owned copy of parsed:

This can be done by writing line_input.push(parsed.to_owned()).

You can also avoid some allocations by re-using buffer if you want to. This can be done by moving let mut buffer = String::new(); outside of the loop and calling buffer.clear() on each iteration.


Thanks. That really helped. Its working now. I am still a bit confused with Rust's concepts of ownership and borrowing. Time to read more books I guess :slight_smile:

Thanks again.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.