#lazy-evaluation #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

#37 in #lazy

Download history 1120/week @ 2024-03-14 1313/week @ 2024-03-21 748/week @ 2024-03-28 305/week @ 2024-04-04 323/week @ 2024-04-11 546/week @ 2024-04-18 573/week @ 2024-04-25 381/week @ 2024-05-02 417/week @ 2024-05-09 282/week @ 2024-05-16 212/week @ 2024-05-23 321/week @ 2024-05-30 480/week @ 2024-06-06 249/week @ 2024-06-13 319/week @ 2024-06-20 384/week @ 2024-06-27

1,541 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

~43KB