A confusion option and result

Hello great community. i have a confussion, this struct have a method find to return a option:
how parse year to i32 ??

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
    }
}

// var to store values 
let mut original_title: Option<&str> = None;
let mut year: Option<&str> = None;  // how convert to i32  or store i32?    :woozy_face:        
let mut country: Option<&str> = None;

let text_file = TextFile::new(/home/pichi/info.txt);
match &text_file {
                        Ok(file) => { //file.print_lines();
                         original_title = Some(file.find("Original title").unwrap().trim());
                         year = Some(file.find("Year").unwrap().trim());                                    
                         country = Some(file.find("Country").unwrap().trim());                        },
                        Err(err) => println!("error {}", err),
                    }

LAST ERROR:
year: year.expect("REASON").parse::(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected Option<i32>, found Result<i32, ParseIntError>

It looks like you omitted the part of the code where the error occurs.

3 Likes

Maybe this is what you mean:

fn example(year: Option<&str>) -> Option<i32> {
    year.and_then(|s| s.parse().ok())
}

But eventually you're going to have some file like

Year
2o17

And wish you had more of a clue as to why there "isn't a year value". I.e. this seems like a case where you want to indicate an error in some way or another. The minimal version of which would be panicking with a very general error:

fn example(year: Option<&str>) -> Option<i32> {
    year.map(|s| s.parse().expect("Could not parse year"))
}
2 Likes