How to filter delete files?

Hey guys. I wanted to create some code to remove certian files.

 let mut from_paths = Vec::new();
 from_paths.push("source/dir1");

 remove_items(&from_paths).unwrap();

But lets say I didn't want to remove a particular file with the name hello.exe. How would I design it as such?

Remove them from the vector first?

lets say the file was located inside source/dir1. How would I then prevent hello.exe from being deleted?

Sounds a job for something like

for p in from_paths.filter(|p| !p.ends_with("hello.exe")) {
  std::fs::remove_file()?;
}

How does this entire thing work? The |p| and How come there is a !p.ends_with("hello.exe") the exclamation mark?

The |p| starts a closure, which is a little function defined right where it is used.

The exclamation mark is the logical "not" operator, since you want to keep only those elements that do not end with hello.exe.

1 Like

Thanks,

Is from_paths inherit from a structure?

I assumed from_paths was the same Vec that you had defined in your code in the original post.

Oh yes it is a vector but it must have some special data type?

Where does the filter() function come from? Is this part of the Rust language?

Filter comes from the standard library.

playground

1 Like

Right I see thanks mate

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.