Generics help: how to accept anything that can become a PathBuf


#1

Basically what the title says. I’d like to be able to accept &str, String, PathBuf, &Path, or anything else that can be converted to a PathBuf. In other words, I’d like to own the data in a PathBuf, but I don’t want to force an extra allocation if someone gives me a PathBuf already, and I don’t care what they give me as long as I will eventually end up with a PathBuf.

It seems like I can get close using ToOwned or Cow, but neither of them do quite what I want. So it looks like this just isn’t possible, but I want to make sure I’m not missing anything first.


#2

There’s a trait for that! https://doc.rust-lang.org/stable/std/convert/trait.Into.html

So something like

fn foo<T: Into<PathBuf>>(buf: T) {
    let buf = buf.into();

#3

Ah perfect, thanks. For some reason, figuring out the correct conversion trait/method to use is the hardest part of Rust for me by far.


#4

“There’s a trait for that!” is a great phrase!
It needs an abbreviation. TaTfT? TTT? 3T?

And a song!
♪There’s a trait for us
Somewhere a trait for us
Peace and quiet and open air…♪


#5

This is a fairly common refrain; it’s tough because there’s a lot of them.