seve
seve

Reputation: 185

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:

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"

Upvotes: 0

Views: 111

Answers (1)

Hamza Jadid
Hamza Jadid

Reputation: 576

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();

Upvotes: 3

Related Questions