Strip Prefix Yields Relative Paths
Turn absolute paths into root-relative display strings with Path::strip_prefix, matching by components rather than raw string prefixes.
Code
use std::path::{Path, PathBuf};
fn relative_to(base: &Path, target: &Path) -> Option<PathBuf> {
// strip_prefix 按“组件”匹配前缀,不是字符串前缀
target.strip_prefix(base).ok().map(Path::to_path_buf)
}
fn main() {
let root = Path::new("/srv/app");
for target in [
"/srv/app/config/nginx.conf",
"/srv/app/logs/gateway.log",
"/etc/other.conf",
] {
match relative_to(root, Path::new(target)) {
Some(rel) => println!("{target} -> {}", rel.display()),
None => println!("{target} is outside base"),
}
}
// 字符串前缀会把 /srv/application 误吞进 /srv/app;组件前缀不会
println!("string prefix lies: {}", "/srv/application".starts_with("/srv/app"));
println!("component prefix strict: {}", Path::new("/srv/application").strip_prefix(root).is_err());
}Inside the code
Under the hood: the functions relative_to and main.
One loop does the cycling here: for target in [. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- Install nothing — the snippet never steps outside the standard library.
Putting it to use
The signature to note is fn relative_to(base: &Path, target: &Path) -> Option<PathBuf>
The demo output is labeled (string prefix lies:, component prefix strict:), so each printed line points back to the operation it originated from.
Start the program and main runs relative_to one after another.
Core lines
fn relative_to(base: &Path, target: &Path) -> Option<PathBuf> {
// strip_prefix 按“组件”匹配前缀,不是字符串前缀
target.strip_prefix(base).ok().map(Path::to_path_buf)
}
match relative_to(root, Path::new(target)) {
Some(rel) => println!("{target} -> {}", rel.display()),
None => println!("{target} is outside base"),
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Strip Prefix Yields Relative Paths print when run?
- Running the file directly is enough — expect labeled output lines such as `string prefix lies:`, `component prefix strict:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.