PathBuf -> impl Into<Cow<'static, str>>

I'm trying to make some of my code a bit less naive by replacing the use of String/&str with Path/PathBuf, in cases where those strings are talking about paths.

Aside:

The code actually appears to be working with the strings, meaning that I'm not aware of the use of strings having caused me any problems in months of running the code. So perhaps I should spend my time on more immediately useful improvements. However, Rust doesn't introduce these complications in order do annoy programmers, but rather to highlight and robustly avoid problems which might otherwise appear. So I'll bang my head against this one for just a little longer in the hope of

  • Learning something
  • Avoiding problems later on

I'm sure my 'improvements' are far from ideal and full of solecisms. For one, I gave up on trying to accept AsRef<Path> (for now) as a whole bunch of short functions were suddenly getting far more fiddly.

My immediate problem is in a program that processes lots of input files. I'm using indicatif to show progress, creating a progress bar using this function:

pub fn with_message(self, message: impl Into<Cow<'static, str>>) -> ProgressBar

Previously, when my paths were represented as Strings, I .clone()d one as the second argument to with_message. Now that they are PathBufs I'm running into all sorts of problems.

How should I turn a PathBuf into something that can be passed into with_message?

Since you were already cloning you could do :

x.with_message(format!("{}", path.display()))
// or
x.with_message(path.display().to_string())
1 Like

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.