【问题标题】:How do I replace the file extension of a PathBuf or Path?如何替换 PathBuf 或 Path 的文件扩展名?
【发布时间】:2019-12-05 22:17:36
【问题描述】:

我目前的解决方案是:

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

这很丑陋,需要至少 6 个函数调用并创建一个新字符串。

有没有更惯用、更短或更有效的方法来做到这一点?

【问题讨论】:

    标签: path rust


    【解决方案1】:

    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");
    

    【讨论】:

    • 谢谢,不知道我是怎么错过的
    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多