文章
rust应用中的“workspace 目录”和“应用根目录”
目录
在 Rust 中,“workspace 目录”和“应用根目录”其实要区分清楚,因为 Rust 编译后运行时是 二进制文件所在位置,而不是源代码目录。所以获取方式有点不同。下面我给你详细整理:#
1️⃣ 获取当前可执行文件所在目录#
这是最常用的“应用根目录”概念(运行时目录):
use std::env;
use std::path::Path;
fn main() {
// 当前可执行文件的路径
let exe_path = env::current_exe().unwrap();
println!("Exe path: {:?}", exe_path);
// 可执行文件所在目录
let exe_dir = exe_path.parent().unwrap();
println!("Exe dir: {:?}", exe_dir);
}
这在二进制发布时最可靠,因为它是程序运行的真实位置。
2️⃣ 获取当前工作目录(程序启动时的目录)#
use std::env;
fn main() {
let current_dir = env::current_dir().unwrap();
println!("Current dir: {:?}", current_dir);
}
默认是启动程序时所在的目录,可以用来读取配置文件、日志目录等。注意:用户可以在任意目录运行程序,这个目录可能不是你的源代码目录。
3️⃣ 开发阶段获取 Cargo workspace 根目录#
如果你是在 开发阶段(比如运行 cargo run),可以通过环境变量 CARGO_MANIFEST_DIR 获取 当前 crate 的 Cargo.toml 所在目录:
fn main() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
println!("Cargo manifest dir: {}", manifest_dir);
}
这是编译时环境变量,宏 env! 会在编译时读取,不占运行时开销。 如果你的项目是 workspace,你可以在 workspace 根目录的 Cargo.toml 里也设置环境变量或者通过相对路径访问子 crate。
总结#
| 场景 | 获取方式 | 说明 |
|---|---|---|
| 运行时应用目录 | std::env::current_exe() | 可执行文件所在目录 |
| 程序启动工作目录 | std::env::current_dir() | 用户运行程序时所在目录 |
| 开发阶段 crate 目录 | env!("CARGO_MANIFEST_DIR") | Cargo.toml 所在目录,编译时固定 |