Borrowed value does not live long enough, Vec<&str>

use std::io::{BufReader, BufRead};
use std::io;

fn read_lines(filename: String) -> io::Lines<BufReader<File>> {
    let file = File::open(filename).unwrap(); 
    return io::BufReader::new(file).lines(); 

pub fn main() {
    let mut doc_reg: Vec<&str> = vec![];
    let mut attach_reg: Vec<Vec<&str>> = vec![];
    let regcontent = read_lines("./config.txt".to_string());
    for line in regcontent{
        let a = line.unwrap();                              # B point
        let c:Vec<&str> = a.split("||").collect();
        if c.get(0).unwrap() == &"K1"{
            doc_reg = c.clone().drain(1..).collect();
        }else if c.get(0).unwrap() == &"K2" {
            let tempvc: Vec<_> = c.clone().drain(1..).collect();
            attach_reg.push(tempvc.clone());       #A point

I add the # A point, then error appers at B point, how to modify to have it works?

The problem is that a gets dropped at the end of the loop, so you can't hold on to a reference into a beyond the loop or for multiple loops.

It's not a problem for doc_reg because you overwrite the entire vector every time. If you stop doing that, it will probably error too.

The fix is to either hold on to String instead of &str, or to hold on to all the lines from the file. The first way is probably the better way.


thanks, great answer solve my problem......

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.