#traits #init #array #vec #2d #array-vec

nightly no-std init_trait

A small helper trait to simplify the initialisation of 'indexable' data structures

2 unstable releases

0.2.0 Aug 21, 2020
0.1.0 Jul 28, 2020

#15 in #array-vec

MIT license

9KB
97 lines

init_trait

Crate

Documentation

Repository

Changelog

A small helper trait to simplify the initialisation of 'indexable' data structures.

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

To use this, add it as a dependency to your Cargo.toml:

[dependencies]
init_trait = "0.2.0"

lib.rs:

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

No runtime deps