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

标签 path rust

我当前的解决方案是:

let temp = format!(
    "{}.png",
    path.file_stem().unwrap().to_string_lossy());
path.pop();
path.push(&temp);
这很丑陋,需要至少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");

关于path - 如何替换PathBuf或Path的文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59204100/

相关文章:

Python在sys.path中搜索文件的方法

matlab - Matlab 中的多个 pathdef 文件?

php - 试图让 php 将文件路径识别为域

ruby - 使用 Ruby FFI 调用 Rust 库时出现段错误

rust - 使用具有泛型类型的运算符时出错

windows - Windows 上的 Rust 回溯?

c# 如何转义具有不同字母的目录路径?

rust - 是否可以将闭包/函数作为结构的成员?

rust - 为什么 if-let 表达式使用赋值运算符而不是相等运算符?

css - Flask 为肯定存在的 css 文件提供 404