0

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);
}
Harry
  • 2,177
  • 1
  • 19
  • 33

2 Answers2

1

The syntax is: static ref NAME: Type = expr;. Note the ref.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
1

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.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
  • which one would you prefer considering the performance(`lazy_static` or `once_cell`)? – Harry Oct 26 '22 at 11:55
  • @Harry I think performance-wise they are absolutely the same. (I haven't seen any benchmark, but this is fairly straight forward as far as I can tell). I prefer `once_cell` simply because I can get rid of a macro. – Lukas Kalbertodt Oct 26 '22 at 13:08