#init #lazy-evaluation #mut #static

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

#36 in #mut

Download history 474/week @ 2024-07-21 436/week @ 2024-07-28 479/week @ 2024-08-04 215/week @ 2024-08-11 196/week @ 2024-08-18 381/week @ 2024-08-25 212/week @ 2024-09-01 384/week @ 2024-09-08 308/week @ 2024-09-15 392/week @ 2024-09-22 454/week @ 2024-09-29 2314/week @ 2024-10-06 734/week @ 2024-10-13 442/week @ 2024-10-20 439/week @ 2024-10-27 233/week @ 2024-11-03

1,870 downloads per month
Used in librstb

MIT license

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

~44KB