[][src]Crate init_trait

A helper trait to inialise data structures using a function applied to each 'index'.

This is intended to simplify the initialisation of 'indexable' data structures to non-default values. For example, if you wanted to initialise a long or arbitrary length array, you would need to first initialise it to some default value, then modify each element to the value you want:

// struct needs to implement either Copy or Default to initialise the array
#[derive(Copy, Clone)]
struct House { number: usize }

// Need to first initialise road to some dummy value to avoid the error:
//     road[i] = House { number: i };
//     ^^^^^^^ use of possibly-uninitialized `road`
let mut road = [House { number: 0 }; 3];

for i in 0..3 {
    road[i] = House { number: i + 1 };
}

assert_eq!(road[0].number, 1);
assert_eq!(road[1].number, 2);
assert_eq!(road[2].number, 3);

This would be difficult for a generic type or a type with no default.

With Init you can instead provide a function to generate the element given the index:

use init_trait::Init;

struct House { number: usize }

// [T; N]: Init<T, usize>
let road = <[House; 3]>::init(|i| House { number: i + 1 });

assert_eq!(road[0].number, 1);
assert_eq!(road[1].number, 2);
assert_eq!(road[2].number, 3);

This also works for types which need some additional information to initialise, such as a run-time length:

use init_trait::Init;

struct House { number: usize }

// Vec<T>: Init<T, usize, usize>
let road = Vec::<House>::init_with(3, |i| House { number: i + 1 });

assert_eq!(road[0].number, 1);
assert_eq!(road[1].number, 2);
assert_eq!(road[2].number, 3);

Traits

Init

Types which can be initialised by applying a function to each 'index' of the type.