iTranslated by AI
Is lazy_static Outdated? Why You Should Use once_cell Instead
3-minute summary of this article
- Rust's global variables had many limitations.
-
lazy_staticis a crate that removes these limitations and makes it easy to use global variables. -
once_cellhas emerged as an alternative tolazy_static.
Rust's global variables had many limitations
Rust does have global variables, but they have limitations:
- They can only be initialized with constants.
- Making them mutable requires the use of
unsafe. - Making them immutable restricts you to thread-safe types only.
These limitations have made them very difficult to use.
For example, let's say you want to load a huge text file once and store it in a global variable.
However, if you write it like this, it becomes a compilation error because you cannot modify a global variable without unsafe.
static mut LARGE_TEXT : String = String::new();
fn main() {
LARGE_TEXT = load_large_text();
}
/// Load huge text
fn load_large_text() -> String {
todo!()
}
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src\main.rs:3:3
|
3 | LARGE_TEXT = load_large_text();
| ^^^^^^^^^^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
Using unsafe would eliminate the compilation error, but it is dangerous because you might accidentally overwrite the text while it is still in use.
static mut LARGE_TEXT: String = String::new();
fn main() {
unsafe {
// Please remember that it is not guaranteed that LARGE_TEXT is not currently in use.
LARGE_TEXT = load_large_text();
}
}
So, what if you use RefCell to get runtime checks to ensure safety? That won't work either, because RefCell is not thread-safe.
use std::cell::RefCell;
static LARGE_TEXT: RefCell<String> = RefCell::new(String::new());
fn main() {
*LARGE_TEXT.borrow_mut() = load_large_text();
}
error[E0277]: `std::cell::RefCell<std::string::String>` cannot be shared between threads safely
--> src\main.rs:2:1
|
2 | static LARGE_TEXT: RefCell<String> = RefCell::new(String::new());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `std::cell::RefCell<std::string::String>` cannot be shared between threads safely
|
= help: the trait `std::marker::Sync` is not implemented for `std::cell::RefCell<std::string::String>`
= note: shared static variables must have a type that implements `Sync`
If that's the case, could you use Mutex, the thread-safe version of RefCell? No, because global variables can only be initialized with constants, so you cannot use it here either.
use std::sync::Mutex;
static LARGE_TEXT: Mutex<String> = Mutex::new(String::new());
fn main() {
*LARGE_TEXT.lock().unwrap() = load_large_text();
}
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> src\main.rs:2:36
|
2 | static LARGE_TEXT: Mutex<String> = Mutex::new(String::new());
|
"Rust's global variables are unusable!"
If you thought that, you are correct. Give up on using global variables as they are and use a crate to make them easier to handle.
lazy_static is a crate that removes these limitations and makes it easy to use global variables
By using lazy_static, you can create global variables that are initialized only once upon their first access.
use lazy_static::lazy_static;
lazy_static! {
static ref LARGE_TEXT: String = load_large_text();
}
fn main() {
println!("{}", *LARGE_TEXT);
}
lazy_static is convenient and quickly established itself as the de facto standard.
However, don't you find lazy_static a bit unintuitive because it relies on macros?
once_cell has emerged as an alternative to lazy_static
Meanwhile, once_cell has appeared, achieving the same processing as lazy_static without using macros.
The previous lazy_static example can be written as follows using once_cell:
use once_cell::sync::Lazy;
static LARGE_TEXT: Lazy<String> = Lazy::new(|| load_large_text());
fn main() {
println!("{}", *LARGE_TEXT);
}
Since it does not use macros, it allows for more advanced applications, such as passing the variable to functions or making it a member of a struct.
fn may_use_large_text(large_text: &Lazy<String>) {
todo!()
}
struct LargeTextCache {
large_text: Lazy<String>,
}
Although its download count has not yet reached that of lazy_static, it is growing rapidly and is even being considered for inclusion in the standard library.
Links
lazy_static
once_cell
Discussion