Edit Path Extensions With PathBuf

Read file_stem and extension, swap suffixes with set_extension and with_extension, and see None for files that never had one.

RustData Integrity

Code

rustsnippet
22 lines
use std::path::PathBuf;

fn main() {
    let mut source = PathBuf::from("reports/q3.csv");

    // 拆出主体与后缀
    println!("stem: {}", source.file_stem().unwrap().to_string_lossy());
    println!("extension: {}", source.extension().unwrap().to_string_lossy());

    // 就地替换扩展名
    source.set_extension("json");
    println!("converted: {source}");

    // with_extension 返回新值,原路径不动
    let archive = source.with_extension("tar.gz");
    println!("archive: {archive}");
    println!("source unchanged: {source}");

    // 没有扩展名的文件:extension 返回 None
    let readme = PathBuf::from("README");
    println!("no extension: {:?}", readme.extension());
}

Splitting a path

file_stem() and extension() on reports/q3.csv print q3 and csv; a file with no extension (README) yields None for extension rather than an empty string.

In place versus fresh

set_extension(“json”) mutates source into reports/q3.json; with_extension(“tar.gz”) returns a new PathBuf (reports/q3.tar.gz) and the source-unchanged line confirms the original was untouched.

Multi-part suffixes

The tar.gz target shows that set/with_extension replace everything after the last dot semantics apply — the resulting name keeps the stem and swaps the whole suffix.

Interactive Tools for This Topic

FAQ

What does extension() return for a file with no extension?
None — not an empty string — which the README line demonstrates and which callers must match on.
How do set_extension and with_extension differ?
set_extension mutates the PathBuf in place; with_extension returns a new PathBuf and leaves the original untouched.