在 Rust 中根据另一个路径格式化文件名的最佳方法

Pal*_*and 2 string path rust

下面有更简洁的写法吗?

use std::path::Path;

let path = Path::new("/path/to/foo.txt");
let formatted = &format!("{}%d.{}", path.file_stem().unwrap().to_str().unwrap(), path.extension().unwrap().to_str().unwrap());

assert_eq!("foo%d.txt", formatted);
Run Code Online (Sandbox Code Playgroud)

(我想转换/path/to/foo.txtfoo%d.txt

She*_*ter 5

不,没有什么比你所拥有的更好的了。路径不是UTF - 8字符串,并且路径可能没有file_stemextension你必须处理所有这些情况,这就是 Rust 成为一门优秀语言的原因。

我唯一可以建议的是完全避免转换为 UTF-8 字符串。您还可以使用占位符空值或在缺少组件时有条件地执行操作:

use std::path::Path;
use std::ffi::OsStr;

fn main() {
    let path = Path::new("/path/to/foo.txt");

    let stem = path.file_stem().unwrap_or(OsStr::new(""));

    let mut filename = stem.to_os_string();
    filename.push("%d.");

    if let Some(extension) = path.extension() {
        filename.push(extension);
    }

    assert_eq!(OsStr::new("foo%d.txt"), filename);
}
Run Code Online (Sandbox Code Playgroud)