Function init_array::init_boxed_array[][src]

pub fn init_boxed_array<T, F, const N: usize>(f: F) -> Box<[T; N]> where
    F: FnMut(usize) -> T, 
Expand description

Initialize a fixed-sized heap-allocated array.

This function takes in a function, which can use the index in the array to compute the value for the item at that index. The function needs to implement FnMut, which means it can also carry internal mutable state which persists for all items.

Thanks to the stabilization of min_const_generics in Rust 1.51, you can use this function to initialize arrays of any length.

Examples

use init_array::init_boxed_array;
assert_eq!(init_boxed_array(|_| 0), Box::new([0; 3]));

assert_eq!(init_boxed_array(|i| i + 1), Box::new([1, 2, 3, 4, 5]));

let mut state = 0;

// arr[i] represents the sum of the first `i + 1` natural numbers.
let arr = init_boxed_array(|i| {
    state += i + 1;
    state
});
assert_eq!(arr, Box::new([1, 3, 6, 10, 15]));