Crate init_with [] [src]

A helper trait to initialize a data structure with custom code.

This crate is meant to aid in initializing fixed arrays using something other than a Default implementation. For example, if you wanted to create an array of Vecs, you could create one with Default that made all the Vecs empty:

let my_array = <[Vec<u32>; 3]>::default();
assert_eq!(my_array, [[], [], []]);

But if you wanted to start the arrays with some state, you either need to start with the empty arrays and fill from there, or drop into unsafe code to write in a partially-initialized array.

let mut my_array = <[Vec<usize>; 3]>::default();

for (idx, arr) in my_array.iter_mut().enumerate() {
    for i in 0..(idx+1) {
        arr.push(i);
    }
}

assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);

With InitWith, the same array could be initialized like this:

use init_with::InitWith;

let my_array = {
    let mut seed = Vec::new();
    let mut next_val = 0;

    <[Vec<u32>; 3]>::init_with(|| {
        seed.push(next_val);
        next_val += 1;
        seed.clone()
    })
};

assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);

Warning: If the function given to init_with panics, any elements that have already been created will not run their destructor. This means that any elements with heap allocations - Vec, Box, etc - will leak their contents.

This crate is built with #![no_std] and only uses libcore for its code, so it can be used from other no_std crates.

Traits

InitWith

A trait that allows you to create an instance of a type with a given function.