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() { GRAPH.slow_function(); }
/// this does not cause lazy static to trigger
pub fn preload2() { let _ = &GRAPH; }
_
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"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.