in

Initialize Rust Constants at Runtime with lazy_static | by Nicholas Obert | Aug, 2023


Outline non-constant static variables with lazy initialization

Picture by Christian Lue on Unsplash

It’s no secret that initializing constants at compile time is an effective apply in programming. Not solely do you cut back the initialization overhead, however you additionally make it simpler for the compiler to cleverly optimize your code by figuring out the worth of the fixed upfront.

Generally, nonetheless, it’s unattainable to initialize each fixed at compile time because it requires performing non-constant operations or fetching information out there solely at runtime. As an example, say we make repetitive use of the quantity √7 in our program. As an alternative of calculating it each time, it might be higher to outline a relentless for it like follows:

const ROOT_OF_SEVEN: f64 = 7_f64.sqrt();

This code, nonetheless, is invalid. The Rust compiler returns the next error:

can not name non-const fn `f64::<impl f64>::sqrt` in constants
calls in constants are restricted to fixed features, tuple structs and tuple variants

The identical occurs if we attempt to initialize a relentless with an setting variable:

const LANG: String = env::var("LANG").unwrap();

From the Rust compiler:

can not name non-const fn `std::env::var::<&str>` in constants
calls in constants are restricted to fixed features, tuple structs and tuple variants

As you’ll be able to see, sure constants that may be helpful to initialize at compile time require non-constant operations. That is the place Rust’s lazy_static crate turns out to be useful. lazy_static lets you outline world static variables that get initialized lazily, that means that their values solely get set upon their very first utilization at runtime. Lazy statics solely should be initialized the primary time they’re used and, since this can be a one-time operation, their runtime initialization overhead is negligible.

On this article, we’ll check out find out how to use Rust’s lazy_static crate to lazily initialize world constants and some of their use instances.

Use lazy_static

To make use of the lazy_static crate, you merely add it to your challenge dependencies by


A Mild Introduction to Bayesian Deep Studying | by François Porcher | Jul, 2023

Chat With Any PDFs and Picture Information Utilizing Massive Language Fashions — With Code | by Zoumana Keita | Aug, 2023