unarray

Function build_array_option

Source
pub fn build_array_option<T, F: FnMut(usize) -> Option<T>, const N: usize>(
    f: F,
) -> Option<[T; N]>
Expand description

Build an array with a function that creates elements based on their value, short-circuiting if any index returns a None

let success = build_array_option(|i| Some(i * 2));
assert_eq!(success, Some([0, 2, 4]));

If f panics, any already-initialized elements will be dropped without running their Drop implmentations, potentially creating resource leaks. Note that this is still “safe”, since Rust’s notion of “safety” doesn’t guarantee destructors are run.

This is similar to the nightly-only core::array::try_from_fn