← 中文资源

简体中文版本

strip_prefix 计算根相对路径

Path::strip_prefix 按组件匹配前缀并返回根相对路径,比字符串 starts_with 精确:/srv/application 不会被 /srv/app 误吞,失败返回错误。

阅读英文原文

实现说明

活动部件是函数 relative_to、main。 文件的主干是一个循环——for target in [。match 表达式是穷尽的——编译器强制没有遗漏的分支。

使用要点

  • 跑完文件,输出里会留下标记——string prefix lies:、component prefix strict:。
  • 运行整个文件:main 会依次驱动 relative_to。

常见问题

运行「strip_prefix 计算根相对路径」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 string prefix lies:、component prefix strict: 这类标签。

签名一览:fn relative_to(base: &Path, target: &Path) -> Option<PathBuf>

核心语句

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"),
}

代码示例

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());
}