Search code examples
rustlazy-static

no rules expected this token in macro call during initialization of static variable using lazy_static crate


I am trying to initialize a static variable at runtime using lazy_static crate. But I'm getting no rules expected the token E1 error while compiling. This is the link lazy_static I followed

use lazy_static::lazy_static;

lazy_static! {
    static E1: f64 = (1.0 - f64::sqrt(1.5)) / (1.0 + f64::sqrt(0.5));
}

fn main() {
    println!("{}", E1);
}

Solution

  • You forgot the ref token after static. This is just some custom grammar of lazy_static to express that this static works a bit different is only accessible by reference.

    use lazy_static::lazy_static;
    
    lazy_static! {
        static ref E1: f64 = (1.0 - f64::sqrt(1.5)) / (1.0 + f64::sqrt(0.5));
        //     ^^^
    }
    
    fn main() {
        println!("{}", *E1);
        //             ^
    }
    

    That's also the reason you need to dereference the value as the static variable is an opaque type. In many contexts this is not required as the type implements Deref<Target = f64>. But here it is.

    Also consider using once_cell which lets you achieve the same thing but without macro.