Function from_fn
const fn from_fn<T, N: usize, F>(f: F) -> [T; N]
where
F: ~const FnMut(usize) -> T
Creates an array where each element is produced by calling f with
that element's index while walking forward through the array.
This is essentially the same as writing
[f(0), f(1), f(2), …, f(N - 2), f(N - 1)]
and is similar to (0..i).map(f), just for arrays not iterators.
If N == 0, this produces an empty array without ever calling f.
Example
// type inference is helping us here, the way `from_fn` knows how many
// elements to produce is the length of array down there: only arrays of
// equal lengths can be compared, so the const generic parameter `N` is
// inferred to be 5, thus creating array of 5 elements.
let array = from_fn;
// indexes are: 0 1 2 3 4
assert_eq!;
let array2: = from_fn;
// indexes are: 0 1 2 3 4 5 6 7
assert_eq!;
let bool_arr = ;
// indexes are: 0 1 2 3 4
assert_eq!;
You can also capture things, for example to create an array full of clones
where you can't just use [item; N] because it's not Copy:
# // TBH `array::repeat` would be better for this, but it's not stable yet.
let my_string = Stringfrom;
let clones: = from_fn;
assert!;
The array is generated in ascending index order, starting from the front and going towards the back, so you can use closures with mutable state:
let mut state = 1;
let a = from_fn;
assert_eq!;