我目前的解决方案是:
let temp = format!(
"{}.png",
path.file_stem().unwrap().to_string_lossy());
path.pop();
path.push(&temp);
Run Code Online (Sandbox Code Playgroud)
这很丑陋,需要至少 6 个函数调用并创建一个新字符串。
有没有更惯用、更短或更有效的方法来做到这一点?
PathBuf提供方法set_extension。如果扩展名尚不存在,它将添加扩展名,如果存在,则将其替换为新的扩展名。
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");
Run Code Online (Sandbox Code Playgroud)