lazy_static将错误引发为“没有规则期望令牌”

问题描述 投票:0回答:1

我正在尝试使用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

我想知道如何解决这个问题?谢谢!

rust
1个回答
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);

reflazy_static语法的一部分,所以你不能把它排除在外。)

© www.soinside.com 2019 - 2024. All rights reserved.