I'm trying to find all files with an specific extension with a function an return a Vec with the paths of all of them. This is my first project in rust and I think I'm stuck here.
This is my function:
I'm using anyhow
for the Result<T>
fn find_file_with_extension_in_path(extension: &str, path: PathBuf) -> Result<Vec<&Path>> {
let matching_files: Vec<&Path> = WalkDir::new(path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| has_extension(e, extension))
.map(|x| x.path())
.collect();
Ok(matching_files)
}
This is the error I get:
error[E0515]: cannot return value referencing function parameter `x`
--> src/main.rs:65:18
|
65 | .map(|x| x.path())
| -^^^^^^^
| |
| returns a value referencing data owned by the current function
| `x` is borrowed here
I don't know how to handle this, and if anyone can give me some pointers why this is happening I would be very glad. Again, I'm quite new to rust and struggling a bit.
The borrow issue goes away if I change:
let matching_files: Vec<&Path> = WalkDir::new(path)
to
let matching_files: Vec<Path> = WalkDir::new(path)
But if I change the return value type to Result<Vec<Path>>
I get this error:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> src/main.rs:60:72
|
60 | fn find_file_with_extension_in_path(extension: &str, path: PathBuf) -> Result<Vec<Path>> {
| ^^^^^^^^^^^^^^^^^ borrow the `Path` instead
|
::: /home/merlin/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/liballoc/vec.rs:300:16
|
300 | pub struct Vec<T> {
| - required by this bound in `std::vec::Vec`
|
Any help with this one or guidance about where to go from here would be appreciated and sorry if this is a bad question in advance.