-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; }
5
  • 1
    Is GRAPH supposed to be DB or vice-versa? Commented Aug 31, 2022 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. Commented Aug 31, 2022 at 22:04
  • @PitaJ: Yes, I forgot to change that from the real code to the example, thanks for noticing me! I fixed that. Commented Sep 1, 2022 at 7:06
  • @ChayimFriedman: I will do that! Interesting that the compiler recommends an external library, I have never seen that before in any language. Commented Sep 1, 2022 at 7: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. Commented Sep 1, 2022 at 7:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 _.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.