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.
Code
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
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.