8176135
8176135

Reputation: 4133

How do I replace the file extension of a PathBuf or Path?

My current solution is:

let temp = format!(
    "{}.png",
    path.file_stem().unwrap().to_string_lossy());
path.pop();
path.push(&temp);

Which is quite ugly, requiring at least 6 function calls and creating an new string.

Is there a more idiomatic, shorter, or more efficient way to do this?

Upvotes: 9

Views: 5556

Answers (1)

E_net4
E_net4

Reputation: 29983

PathBuf provides the method set_extension. It will add the extension if one does not exist yet, or replace it with the new one if it does.

let mut path = PathBuf::from("path/to/file");
path.set_extension("png");
assert_eq!(&path.to_string_lossy(), "path/to/file.png");

let mut path = PathBuf::from("path/to/file.jpg");
path.set_extension("png");
assert_eq!(&path.to_string_lossy(), "path/to/file.png");

Upvotes: 19

Related Questions