Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting a for loop into filter_map expression

I’m new to rust and trying to explore the various methods available on the types.

I’m trying to improve the CLI walkthrough using iterator methods but am struggling with filter_map.

// Create a vector of String to hold lines where the pattern was found
let mut findings: Vec<String> = Vec::new();

// BufReader created above
for line in reader.lines() {
    match line {
        Ok(pattern) => {
            if pattern.contains(&args.pattern) {
                findings.push(pattern);
            }
         },
         Err(failure) => {
             println!("No lines in buffer")
         }
    };
}

I’m trying to shorten this using the iterator methods available but can’t seem to figure out how to use filter_map to return lines where the pattern matched:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let mut coll:Vec<String> = reader.lines()
    .filter_map(|line| line.ok())  // <-- What should go here?
    .collect();

I’m not sure how to add the "include lines where pattern.contains(&args.pattern) returns true"

>Solution :

You should use flatmap to clear the None after using ok(), then filter using a predicate.

let mut coll: Vec<String> = reader.lines()
    .flat_map(|line| line.ok())
    .filter(|pattern| pattern.contains(&args.pattern))
    .collect();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading