← 中文资源

简体中文版本

Current Dir 锚定相对路径

用 env::current_dir 取得绝对起点再拼接相对路径,这样无论从哪个目录启动工具,都能定位到同一组文件。

阅读英文原文

实现说明

除了函数 anchor、main,文件里再无其他定义。 错误装在 Result 里往回传,迫使每个调用点显式决策。

使用要点

  • 错误走 Result 通道;改编时若去掉 ?,每个调用点都要自己 match。
  • 每一步打印都带着自己的标签:base:、absolute:、config:。
  • 执行文件,main 会按顺序走完 anchor。

常见问题

错误怎么传到调用方?

通过 Result 值,用 ? 运算符向上传播。示例内部没有 panic,如何处理每次失败由调用方决定。

运行「Current Dir 锚定相对路径」会打印什么?

整个文件跑完,输出行以 base:、absolute:、config: 这类前缀开头。

入口签名:fn anchor(relative: &str) -> std::io::Result<PathBuf>

核心语句

fn anchor(relative: &str) -> std::io::Result<PathBuf> {
    let base = env::current_dir()?;
    // current_dir gives an absolute starting point for the join
    Ok(base.join(relative))
}

代码示例

use std::env;
use std::path::{Path, PathBuf};

fn anchor(relative: &str) -> std::io::Result<PathBuf> {
    let base = env::current_dir()?;
    // current_dir gives an absolute starting point for the join
    Ok(base.join(relative))
}

fn main() {
    let base = env::current_dir().expect("current dir readable");
    println!("base: {}", base.display());
    println!("absolute: {}", base.is_absolute());

    let config = anchor("config/app.toml").expect("anchor works");
    println!("config: {}", config.display());
    println!("starts with base: {}", config.starts_with(&base));

    let raw = Path::new("logs");
    println!("relative stays relative: {}", !raw.is_absolute());
    println!("joined name: {:?}", base.join(raw).file_name());
}