Let's say that I would like to have a list of all *.conf files from the "/etc" directory. The intuitive way to do this is by using read_dir and filter with .path().ends_with(".conf"), but it does not seem to work. Am I using the API wrong or is it a bug?
The issue with your code is n is a &Result<DirEntry, std::io::Error> - filter() only gives you a reference to the underlying value of the iterator. So if you're going to pattern match it, you need to do if let &Ok(ref file) = n { ... }. Alternatively, you can deref n: if let Ok(ref file) = *n { ... }
Thank you! I totally missed this, because I didn't understand the second line in documentation: Only considers whole path components to match. (Path in std::path - Rust).
Do you think it is a good idea to submit a PR with extended documentation for this method? To prevent others from the same confusion and stress the fact, that you cannot match the same way as with strings.
EDIT: alternative with extension method
use std::fs;
fn main() {
println!("Version 1:");
let files = fs::read_dir("/etc").unwrap();
files
.filter_map(Result::ok)
.filter_map(|d| d.path().to_str().and_then(|f| if f.ends_with(".conf") { Some(d) } else { None }))
.for_each(|f| println!("{:?}", f));
println!("Version 2:");
let files = fs::read_dir("/etc").unwrap();
files
.filter_map(Result::ok)
.filter(|d| if let Some(e) = d.path().extension() { e == "conf" } else {false})
.for_each(|f| println!("{:?}", f));
}