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.

Thanks
Girish

pub fn persist_strings()
{
// vairable declarations.

let mut line_input = Vec::new();


loop
{

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

}

Error -
error[E0597]: buffer does not live long enough
--> src/file_ops.rs:43:30
|
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.

2 Likes

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.
Best
Girish