我正在尝试使用lazy_static板条箱初始化一些静态变量,这些静态变量通过读取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
我想知道如何解决该问题?谢谢!
答案 0 :(得分:1)
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
语法的一部分,因此您不能忽略它。)