Append an additional extension?


Let’s say I have a Path:, and I’d like to append an extension baz to get: Right now there seem to be no easy way to do it.


Remember that Path is analogous to str and that PathBuf is likewise analogous to String, and you can build on it.


How? I can’t format! or append_str to a PathBuf. Everything is working on component level, plus couple of methods for extension and file stem. Am I missing something?


Well, if you want it in your format, then you can push and then replace on a .to_string call to replace / with .. I’m on mobile so I can’t add a playground example


No. I want a PathBuf. I need to rename a directory to a ${original_dir}.tmp, but the original_dir might already have dots in it.


Why not try the following:

  1. Get the last component in path_buf.components() and cast it’s as_os_str to an owned string
  2. Add what you want to it
  3. Call pop on path_buf
  4. Push your new string onto your path_buf

This is missing a check to make sure that it is a directory, so be sure that it either is, or run some checks on user input
Edit: it’s actually abit more complicated than that because it doesn’t go straight to String and instead its os variant, so that’s something to keep in mind


Yeah, so I have something like this, but it’s terribly clunky. I’m surprised that stdlib provided methods to replace the extension, but not append, which is usually what I would actually like (eg. for tmp files etc)


Oh, what about a cleaner way where you call into_os_string on the pathbuf and just append and form a new pathbuf?
I know that this isn’t very non-clunky but I can’t figure out another way without some better context


How do you append to OsString without converting to Vec<u8>?


You can push as better exemplified by the examples on the docs


I’ve totally missed it. Thank you!