Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does sort_by_key really need 'static lifetime? #202

Open
dbarnett opened this issue Sep 9, 2024 · 3 comments · May be fixed by #203
Open

Does sort_by_key really need 'static lifetime? #202

dbarnett opened this issue Sep 9, 2024 · 3 comments · May be fixed by #203

Comments

@dbarnett
Copy link

dbarnett commented Sep 9, 2024

I hit a snag with lifetimes and wondered: is it intentional that WalkDir.sort_by_key requires a 'static lifetime on its func argument instead of just the same lifetime as the WalkDir?

I was trying to do something like this:

let walker = WalkDir::new(path)
    .sort_by_key(|e| {
        let relative_path = e.path().strip_prefix(path).unwrap();
        some_func(relative_path)
    })

and that failed saying my path didn't live long enough for the required 'static lifetime, even though it does live until after walker was used and dropped.

@BurntSushi
Copy link
Owner

I would suggest putting path into an Arc. Either that, or just cloning it and moving it into the closure. Either should be marginal costs relative to recursive directory traversal.

@dbarnett
Copy link
Author

Hmm, hate to ask but could you give an example? I tried something like:

    pub my_func<P: AsRef<Path> + Copy>(&mut self, path: P) {
        let path = Arc::new(path);
        let walker = WalkDir::new(path.clone().as_ref())
            .sort_by_key(move |e| {
                let relative_path = e.path().strip_prefix(path.clone().as_ref()).unwrap();
                some_func(relative_path)
            })}

but I keep getting lifetime errors about "`P` may not live long enough ... for the static lifetime".

@BurntSushi
Copy link
Owner

Your Arc in that example looks like it has a lifetime attached to it. Make sure it has type Arc<PathBuf>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants