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. # Examples ```rust # #![allow(unused)] # extern crate array_init; # // Initialize an array of length 50 containing // successive squares let arr: [usize; 50] = array_init::array_init(|i| i * i); assert!(
(mut initializer: F)
| 68 | /// assert!(arr.iter().enumerate().all(|(i, &x)| x == i * i)); |
| 69 | /// ``` |
| 70 | pub fn array_init<F, T, const N: usize>(mut initializer: F) -> [T; N] |
| 71 | where |
| 72 | F: FnMut(usize) -> T, |
| 73 | { |
| 74 | enum Unreachable {} |
| 75 | |
| 76 | try_array_init( |
| 77 | // monomorphise into an infallible version |
| 78 | move |i| -> Result<T, Unreachable> { Ok(initializer(i)) }, |
| 79 | ) |
| 80 | .unwrap_or_else( |
| 81 | // zero-cost unwrap |
| 82 | |unreachable| match unreachable { /* ! */ }, |
| 83 | ) |
| 84 | } |
| 85 | |
| 86 | #[inline] |
| 87 | /// Initialize an array given an iterator |