pub fn get_files(path: String) {
for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()){
if entry.file_type().is_file() {
if entry.path().display().to_string().ends_with(".mp3"){
println!("{}",entry.path().display());
}
}
}}
hi guys i use this function to check for the available mp3 files in given folder. now i need to check the mp3 and flac files. rather than using if else how can i achieve this?.
Things I would change:
.extension()
instead of weirdly converting into a string and then matching that with .ends_with()
match
if you want to handle multiple endingsString
as a parameter - use &str
instead. It is almost always better and more general.String
or &str
- it uses AsRef<Path>
, as can also be seen in the std library and WalkDir.use std::{ffi::OsStr, path::Path};
use walkdir::WalkDir;
pub fn get_files(path: impl AsRef<Path>) {
for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
if entry.file_type().is_file() {
let path = entry.path();
if let Some(extension) = path.extension().and_then(OsStr::to_str) {
match extension {
"mp3" => println!("MP3: {}", path.display()),
"flac" => println!("FLAC: {}", path.display()),
_ => (),
}
}
}
}
}
If you dislike the if let Some
followed by match
, you can also combine them. Which one you choose is personal preference.
use std::{ffi::OsStr, path::Path};
use walkdir::WalkDir;
pub fn get_files(path: impl AsRef<Path>) {
for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
if entry.file_type().is_file() {
let path = entry.path();
match path.extension().and_then(OsStr::to_str) {
Some("mp3") => println!("MP3: {}", path.display()),
Some("flac") => println!("FLAC: {}", path.display()),
_ => (),
}
}
}
}