我正在尝试使用lazy_static crate来初始化一些静态变量,这些变量通过读取build.rs
中的一些环境变量来赋值。我想要实现的是类似于this post。
我的代码如下:
lazy_static! {
static _spdk_dir : String = match env::var("SPDK_DIR") {
Ok(val) => val,
Err(_e) => panic!("SPDK_DIR is not defined in the environment")
};
static _dpdk_dir: String = match env::var("DPDK_DIR") {
Ok(val) => val,
Err(_e) => panic!("DPDK_DIR is not defined in the environment")
};
}
运行cargo test
后,编译器会给出error: no rules expected the token _spdk_dir
。我可以通过在ref
之后添加关键字static
来消除此错误,但这样做会在使用println!
变量时导致另一个错误:
println!("cargo:warning={}", _spdk_dir);
错误是_spdk_dir doesn't implement std::fmt::Display
我想知道如何解决这个问题?谢谢!
Under the hood, lazy_static
creates a one-off object that dereferences to the actual value, which is computed lazily. _spdk_dir
不是String
,而是评估为String
的值。您需要取消引用该值才能打印它。你可以做的另一件事是使用unwrap_or_else
而不是match
:
lazy_static! {
static ref _spdk_dir: String = env::var("SPDK_DIR")
.unwrap_or_else(|_| panic!("SPDK_DIR is not defined in the environment"));
static ref _dpdk_dir: String = env::var("DPDK_DIR")
.unwrap_or_else(|_| panic!("DPDK_DIR is not defined in the environment"))
}
println!("cargo:warning={}", *_spdk_dir);
(ref
是lazy_static
语法的一部分,所以你不能把它排除在外。)