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) {

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(|| {
        next_val += 1;

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

Alternatively, init_with_indices can be used to more easily create array entries based on their index:

use init_with::InitWith;

let squares = <[usize; 5]>::init_with_indices(|i| i*i);

assert_eq!(squares, [0,1,4,9,16]);

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



A trait that allows you to create an instance of a type by using a given function to generate each element.