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