Path and Filesystem Models
Path File Parts
Read Name and Extension
Path can inspect filename-shaped text without opening or reading from the filesystem.
Program
Play the program to choose a path string and inspect its final name and extension.
path_file_parts.rs
use std::path::Path;
fn main() {
let raw = ;
let path = Path::new(raw);
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or("none");
let ext = path.extension().and_then(|name| name.to_str()).unwrap_or("none");
println!("{file}:{ext}");
}
use std::path::Path;
fn main() {
let raw = ;
let path = Path::new(raw);
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or("none");
let ext = path.extension().and_then(|name| name.to_str()).unwrap_or("none");
println!("{file}:{ext}");
}
use std::path::Path;
fn main() {
let raw = ;
let path = Path::new(raw);
let file = path.file_name().and_then(|name| name.to_str()).unwrap_or("none");
let ext = path.extension().and_then(|name| name.to_str()).unwrap_or("none");
println!("{file}:{ext}");
}
Path
`Path::new` treats a string as path-shaped data without touching the filesystem.
file_name
`file_name` returns the last component when one is present.
extension
`extension` returns the text after the last dot in the filename.