Function std::array::from_fn

1.63.0 · source ·
pub fn from_fn<T, const N: usize, F>(cb: F) -> [T; N]where
    F: FnMut(usize) -> T,
Expand description

Creates an array [T; N] where each array element T is returned by the cb call.

Arguments

  • cb: Callback where the passed argument is the current array index.

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 = core::array::from_fn(|i| i);
assert_eq!(array, [0, 1, 2, 3, 4]);
Run