我正在尝试使用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。我可以通过在static后面添加关键字ref来消除这个错误,但是在println!中使用变量时,这样做会导致另一个错误
println!("cargo:warning={}", _spdk_dir);错误为_spdk_dir doesn't implement std::fmt::Display
我想知道我怎样才能解决这个问题?谢谢!
发布于 2018-09-03 02:10:09
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语法的一部分,所以您不能省略它。)
https://stackoverflow.com/questions/52139667
复制相似问题