1 unstable release
Uses old Rust 2015
0.1.0 | Mar 11, 2018 |
---|
#37 in #lazy
1,541 downloads per month
Used in librstb
9KB
122 lines
lazy_mut
lib.rs
:
This crate provides a structure that can be used to lazily initialized values as well as a macro for creating lazy variables.
LazyMut<T>
dereferences to T
, however it will throw an error if it is dereferenced immutably
before it is initialized. Mutable dereferences are allowed and will automatically initialize the
variable, to allow assignments like *VEC = vec![1, 2, 3]
on an uninitialized VEC
. You
should still include the explicit initialization for clarity, even if it is unnecessary.
Local Variables
Using the lazy_mut
macro makes declaring lazy variables easier:
#[macro_use]
extern crate lazy_mut;
lazy_mut! {
let mut num: u32 = 2 + 3;
}
num.init();
assert_eq!(*num, 5);
Another, more lengthy way to write this would be:
use lazy_mut::LazyMut;
let mut num = {
fn init() -> u32 { 2 + 3 }
LazyMut::Init(init)
};
num.init();
assert_eq!(*num, 5);
The function definition makes this code harder to read and understand than the example with the
macro. However, this code does emphasize the fact that the variable is lazy and must be
initialized before use. You should consider this trade-off when choosing how to use LazyMut
.
Static Variables
The lazy_mut
macro also works for static variables:
#[macro_use]
extern crate lazy_mut;
lazy_mut! {
static mut VEC: Vec<u64> = Vec::new();
}
VEC.init(); // Although technically unnecessary, it is more clear to explicitly initialize it
VEC.push(17);
VEC.push(64);
assert_eq!(*VEC, vec![17, 64]);
Another way to write this would be:
use lazy_mut::LazyMut;
static mut VEC: LazyMut<Vec<u64>> = LazyMut::Init(Vec::new);
VEC.push(17);
VEC.push(64);
assert_eq!(*VEC, vec![17, 64]);
Note that with the direct definition the function Vec::new
can be passed directly, making it
simpler to write. LazyMut
can be used to make simple initializers for types that require heap
allocations at runtime, such as collections, strings, or boxed types.
Dependencies
~43KB