Function array_init::array_init[][src]

pub fn array_init<Array, F>(initializer: F) -> Array where
    Array: IsArray,
    F: FnMut(usize) -> Array::Item

Initialize an array given an initializer expression

The initializer is given the index of the element. It is allowed to mutate external state; we will always initialize the elements in order.

Without the nightly feature it is very likely that this will cause memcpys. For panic safety, we internally use NoDrop, which will ensure that panics in the initializer will not cause the array to be prematurely dropped. If you are using a Copy type, prefer using array_init_copy since it does not need the panic safety stuff and is more likely to have no memcpys.

If your initializer panics, any elements that have been initialized will be leaked.

Examples


// Initialize an array of length 10 containing
// successive squares

let arr: [u32; 50] = array_init::array_init(|i| (i*i) as u32);

// Initialize an array from an iterator
// producing an array of [1,2,3,4] repeated

let four = [1u32,2,3,4];
let mut iter = four.iter().cloned().cycle();
let arr: [u32; 50] = array_init::from_iter(iter).unwrap();