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 realizing 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 obtainable solely at runtime. As an illustration, say we make repetitive use of the quantity √7
in our program. As a substitute of calculating it each time, it could 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 capabilities, 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 capabilities, tuple structs and tuple variants
As you may see, sure constants that will be helpful to initialize at compile time require non-constant operations. That is the place Rust’s lazy_static
crate is useful. lazy_static
means that you can outline international static variables that get initialized lazily, which means that their values solely get set upon their very first utilization at runtime. Lazy statics solely have to 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 the way to use Rust’s lazy_static
crate to lazily initialize international 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