Function init_array::init_boxed_slice [−][src]
pub fn init_boxed_slice<T, F>(n: usize, f: F) -> Box<[T]> where
F: FnMut(usize) -> T,
Expand description
Initialize a dynamically-sized heap-allocated slice.
This function takes in the length of the returned slice as well as 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.
Examples
use init_array::init_boxed_slice; assert_eq!(&*init_boxed_slice(3, |_| 0), &[0; 3]); assert_eq!(&*init_boxed_slice(5, |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_boxed_slice(5, |i| { state += i + 1; state }); assert_eq!(&*arr, &[1, 3, 6, 10, 15]);