1

I'm trying to use lazy_static crate to initialize some static variables which assigned values by reading some environment variables in build.rs. What I'm trying to achieve is similar to this post.

My code is following:

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

After running cargo test, the compiler gives error: no rules expected the token _spdk_dir. I can get rid of this error by adding the keyword ref after static but doing so will lead another error when use the variable with println!:

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

The error is _spdk_dir doesn't implement std::fmt::Display

I'm wondering how can I solve the problem? Thanks!

xxks-kkk
  • 2,336
  • 3
  • 28
  • 48
  • 3
    Possible duplicate of [Why does a lazy-static value claim to not implement a trait that it clearly implements?](https://stackoverflow.com/questions/48114390/why-does-a-lazy-static-value-claim-to-not-implement-a-trait-that-it-clearly-impl) – Stargateur Sep 02 '18 at 19:21

1 Answers1

3

Under the hood, lazy_static creates a one-off object that dereferences to the actual value, which is computed lazily. _spdk_dir is not a String but a value that evaluates to a String. You need to dereference the value to print it. One other thing you can do is use unwrap_or_else instead of the 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 is part of lazy_static’s syntax, so you can’t leave it out.)

Aankhen
  • 2,198
  • 11
  • 19