gpt4 book ai didi

rust - lazy_static 引发错误为 "no rules expected the token"

转载 作者:行者123 更新时间:2023-11-29 08:29:29 25 4
gpt4 key购买 nike

我正在尝试使用 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。我可以通过在 static 之后添加关键字 ref 来摆脱这个错误但是这样做会导致在 println! 中使用变量时出现另一个错误:

println!("cargo:warning={}", _spdk_dir);

错误是 _spdk_dir 没有实现 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而不是 匹配:

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);

(reflazy_static 语法的一部分,所以你不能省略它。)

关于rust - lazy_static 引发错误为 "no rules expected the token",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52139667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com