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.

RustConfig Management

Code

rustsnippet
25 lines
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

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:`.