Function init_array::init_array [−][src]
pub fn init_array<T, F, const N: usize>(f: F) -> [T; N] where
F: FnMut(usize) -> T,
Expand description
Initialize a fixed-sized stack-based 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_array; assert_eq!(init_array(|_| 0), [0; 3]); assert_eq!(init_array(|i| i + 1), [1, 2, 3, 4, 5]); let mut state = 0; // arr[i] represents the sum of the first `i + 1` natural numbers. let arr = init_array(|i| { state += i + 1; state }); assert_eq!(arr, [1, 3, 6, 10, 15]);