简体   繁体   中英

How do I change the file name of a path without changing its directory or extension?

What's the best way to implement the change_file_name function?

let path = Path::new("/path/to/file.rs");
let new_path = change_file_name(&path, "new_file_name") // -> "/path/to/new_file_name.rs"

Take something that can be referenced as a Path , then pop off the existing filename, replacing it and preserving the optional extension:

use std::path::{Path, PathBuf};

fn change_file_name(path: impl AsRef<Path>, name: &str) -> PathBuf {
    let path = path.as_ref();
    let mut result = path.to_owned();
    result.set_file_name(name);
    if let Some(ext) = path.extension() {
        result.set_extension(ext);
    }
    result
}

fn main() {
    let path = "/path/to/file.rs";
    let new_path = change_file_name(path, "new_file_name");
    assert_eq!(new_path, Path::new("/path/to/new_file_name.rs"));
}

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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