-1

I use Rust's lazy_static crate to assign a frequently used database object to a global variable but I do not want lazy loading. Is there a way to trigger lazy_static to preload the variable or is there a better way to achieve this? All the functions of the database are expensive and it seems to not be enough to assign a reference.

lazy_static! {
    static ref DB: DataBase = load_db();
}
 
/// this is too slow
#[allow(unused_must_use)] 
pub fn preload1() { DB.slow_function(); }

/// this does not cause lazy static to trigger
pub fn preload2() { let _ = &DB; }
Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118
  • 1
    Is `GRAPH` supposed to be `DB` or vice-versa? – PitaJ Aug 31 '22 at 16:32
  • Nit: Do not use `lazy_static`, use `once_cell`, its API is going to be integrated into std [and now it is even recommended by the compiler](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=f6798175c1c9b88d4a2d67b9ec91d68b). – Chayim Friedman Aug 31 '22 at 22:04
  • @PitaJ: Yes, I forgot to change that from the real code to the example, thanks for noticing me! I fixed that. – Konrad Höffner Sep 01 '22 at 07:06
  • @ChayimFriedman: I will do that! Interesting that the compiler recommends an external library, I have never seen that before in any language. – Konrad Höffner Sep 01 '22 at 07:08
  • 1
    @KonradHöffner It was indeed doubted whether this should be implemented, but was now mainly because it is going to be part of the standard library. – Chayim Friedman Sep 01 '22 at 07:15

1 Answers1

1

_ does not bind, so use a variable name (with leading underscore to avoid the lint):

use lazy_static::lazy_static; // 1.4.0

struct DataBase;
fn load_db() -> DataBase {
    println!("db loaded");
    DataBase
}

lazy_static! {
    static ref DB: DataBase = load_db();
}

fn main() {
    let _db: &DataBase = &*DB; // prints "db loaded"
}

playground

PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • 1
    The problem is not the `_`, it's the `&` that should be `&*`. Another solution is to type annotate as `&DataBase` to force a deref coercion, even with `_`. – Chayim Friedman Aug 31 '22 at 22:05