How to get a filename string (with default) from Option<PathBuf>?

This seems like it should be relatively straightforward, but I'm at a loss on how to accomplish this.
I tried:

let filename = path
    .and_then(|name| name.file_name())
    .and_then(|name| name.to_str())
    .unwrap_or("default");

But I get

error[E0515]: cannot return value referencing function parameter `name`

And I don't know what to do from here.

Use Option::as_ref so that and_then will borrow the PathBuf instead of consuming and dropping it:

let filename = path
    .as_ref()
    .and_then(|name| name.file_name())
    .and_then(|name| name.to_str())
    .unwrap_or("default");
3 Likes

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.