There's more...

People coming from other languages might wonder what lazy_static offers that can't already be done by a normal static object. The difference between them is as follows.

In Rust, a static variable is a variable that lives for the entire duration of the program, which is why they get their own, special lifetime, 'static. The catch is that the variable has to be built in a constant way, that is, a way that is known at compile time. In our example, we cannot replace CURRENCIES [11] with a normal static because HashMap::new() returns a newly constructed HashMap sitting somewhere in the memory during runtime. As this requires it to live in memory, it's impossible to build a HashMap during compile time, so its constructor is not constant.

Another catch with static variables is that, because they have a global lifetime, the borrow checker cannot make sure that their access is thread-safe. As a consequence, any access on a static mut variable will always be unsafe.

The convention for static variables is to write them in ALL_CAPS, just like const variables. This is because they are very closely linked. In fact, a const is nothing but an inlined static that can never be mut.

lazy_static gets around these restrictions by wrapping your object in a newly created struct that can be implicitly dereferenced into your object. This means that you never actually access your object directly. lazy_static stresses this by demanding that you write ref during the declaration of the static, as this makes you mentally treat the variable as a reference rather than an actual object:

lazy_static! {
static ref foo: Foo = Foo::new();
}

While dereferencing, the wrapper struct works with a static mut pointer in your dynamically created object. All it does then is wrap the unsafe calls in a safe way.

If you come from a modern C++ background, you can view a normal static Rust as a static constexpr C++ and a lazy_static Rust as a static C++ local.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.26.217