#lazy #mut #static #init

lazy_mut

This crate provides a structure that can be used to lazily initialized values as well as a macro for creating lazy variables

1 unstable release

Uses old Rust 2015

0.1.0 Mar 11, 2018

#10 in #init

Download history 4/week @ 2020-08-01 4/week @ 2020-08-08 10/week @ 2020-08-15 7/week @ 2020-08-22 4/week @ 2020-08-29 508/week @ 2020-09-05 533/week @ 2020-09-12 284/week @ 2020-09-19 275/week @ 2020-09-26 244/week @ 2020-10-03 11/week @ 2020-10-10 12/week @ 2020-10-17 7/week @ 2020-10-24 18/week @ 2020-10-31 30/week @ 2020-11-07 5/week @ 2020-11-14

441 downloads per month

MIT license

8KB
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;

# fn main() {
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();
}

# fn main() {
# unsafe {
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);

# fn main() {
# unsafe {
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

~28KB