Append some characters to `Path`

Hello all!

I’m playing with Path. I have a Path and want to add a ".spv" to the end. Like this:

"./foo/bar.vert" -> "./foo/bar.vert.spv"

So far, here is what I have:

let path = "./foo/bar.vert";
let spirv_path = path.to_path_buf().into_os_string().into_string().unwrap() + ".spv";
let mut spirv_path = Path::new(&spirv_path);

Looks convoluted for a such simple task. I'm sure there is a better way to do this.

Any advise?

Playground link

A big thanks in advance!

If you know that the original path ends with ".vert" then you can do this:

let spirv_path = path.with_extension("vert.spv");

If you don't know the original extension, you can do this:

let mut name = path.file_name().unwrap().to_owned();
name.push(".spv");
let spirv_path = path.with_file_name(name);
1 Like

Your second example looks more expressive than mine, I will go with it.

Thanks a lot ! :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.