Can't return a vector of Path from a function

177 | fn find_files(res: Vec<Regex>) -> Vec<Path>
    |                                   ^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Path`, the trait `Sized` is not implemented for `[u8]`
    = note: required because it appears within the type `Path`
note: required by a bound in `Vec`

Originally I returned a vector of Strings but since I was going to use them in

for file_name in files {
            let file = match File::open(&file_name) {

It felt more efficient to return Path instead since open() takes Path anyway. Is there some clever thing I can do or just go back to returning a vector of strings?

You want to return a Vec<PathBuf> here. Path is the equivalent of str, so doesn't own the data.

Ah OK I need to use PathBuf instead. Thanks, I'll see if I can get that to work.

Is there an easy way to convert from Path to PathBuf? (hunting around stackoverflow as I type). Maybe it is why all the examples I've seen convert them to strings via to_lossy_string().

Path::to_path_buf() is what you want. This is the path equivalent of str::to_string() - allocate a new owned buffer to hold a copy of the original data.

1 Like

Thanks. I'll look into that too. This also seemed to compile for me as well

  let dir_filter = | entry: Result<DirEntry,Error>| {
        match entry {
            Ok(entry) => {
                if entry.file_type().is_file() {
                    Some(PathBuf::from(entry.path()))
                } else {
                    None
                }
            },
            Err(_err) => None,
       }
    };
        match entry {
            Ok(entry) => {
                if entry.file_type().is_file() {
                    Some(entry.path().to_path_buf())
                    // Some(PathBuf::from(entry.path()))
                } else {
                    None
                }
            },
            Err(_err) => None,
       }
    };

Also works. Now to ponder the difference :slight_smile: .

There is no difference. There are often multiple ways to write a type conversion, as there are several different traits that deal with converting types as well as intrinsic methods on types for common cases.

2 Likes

You shouldn't have to convert anything here at all, though. std::fs::DirEntry::path() already returns a PathBuf: DirEntry in std::fs - Rust

2 Likes

I'm actually using walkdir version of DirEntry (sorry for not making that clear). Looking at the docs I see there is an into_path(). This looks good.

 if entry.file_type().is_file() {
                    Some(entry.into_path())
                    // Some(PathBuf::from(entry.path()))
                } else 

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.