Rust 获取项目文件夹的绝对路径
2021-08-15 本文已影响0人
找不到工作
在写某个玩具项目的时候,需要在 integration test 中读取某个复杂的配置文件。而读取这个文件本身也是测试的一部分。目录结构如下:
Proj
|- src
|- tests
|- my_tests.rs
|- some.conf
但是使用 cargo test
时,执行目录并不确定(可以更改 target 路径),因此这里必须在代码中使用绝对路径读取 some.conf
。
好在 Rust 确实隐蔽地提供了这么一个功能,因为 Cargo 在编译时必须知道项目的位置,因此会设置一个环境变量 CARGO_MANIFEST_DIR
。这个环境变量就是 Cargo.toml
文件所在的文件夹,也就是 项目文件夹的绝对路径。通过它,我们可以自己手动拼接一个 some.conf
的绝对路径:
use std::path::PathBuf;
#[test]
fn test_something() {
// omitted...
let mut config_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
config_path.push("tests");
config_path.push("some.conf");
println!("config file: {:?}", config_path);
// omitted...
}