简体   繁体   English

如何替换 PathBuf 或 Path 的文件扩展名?

[英]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.这很丑陋,需要至少 6 个函数调用并创建一个新字符串。

Is there a more idiomatic, shorter, or more efficient way to do this?有没有更惯用、更短或更有效的方法来做到这一点?

PathBuf provides the method set_extension . PathBuf提供了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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM