Struct to read info.txt, problem

Hi everyone, i need read a info.txt, to extract a certain data line.
this is my code:

struct TextFile {
    lines: Vec<String>,
}

impl TextFile {
    fn new(filename: &str) -> io::Result<TextFile> {
        let reader = fs::read_to_string(filename)
                                    .expect("Except: file info.txt not exist");    
        let liness = reader.lines();
        let lines: Vec<String> = liness.map(String::from).collect(); // can't iterate &str to gain a vec of String
        
        Ok(TextFile {lines})
    }
    
    fn _print_lines(&self) {
        for line in &self.lines {
            println!("{}", line);
        }
    }
    
    fn find(&self, key: &str) -> Option<&str> {
        let mut found: bool = false;
        for line in &self.lines {
            // ... you know you return the line AFTER the line where you found `key`, right?
            if found {
                return Some(line);
            } else if line.contains(key) {
                found = true;
            }
        }
        None
    }
}

let mut original_title: Option<&str> = None;            
    let mut year: Option<&str> = None;
    
    let filename = "/home/pichibw/info.txt";
    let text_file = TextFile::new(&filename);
                        match text_file {
                            Ok(file) => {
                                    original_title = Some(file.find("Original title").unwrap().trim());
                                    year = Some(file.find("Year").unwrap().trim());                                
                            },
                            Err(err) => println!("error {}", err),
    }
println!("value of a: {}", &original_title.unwrap());

this is my error :
error[E0597]: file does not live long enough
--> src/main.rs:2041:59
|
2040 | Ok(file) => {
| ---- binding file declared here
2041 | original_title = Some(file.find("Título original").unwrap().trim());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
2042 | year = Some(file.find("Año").unwrap().trim()); ...
2043 | },
| - file dropped here while still borrowed
...
2049 | println!("value of a: {}", &original_title.unwrap());
| -------------- borrow later used here

You are matching on the text_file by value, which means that it will be dropped at the end of the match. You should match on a reference to that variable instead.

2 Likes

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.