Function std::array::try_from_fn[][src]

pub fn try_from_fn<E, F, T, const N: usize>(cb: F) -> Result<[T; N], E> where
    F: FnMut(usize) -> Result<T, E>, 
🔬 This is a nightly-only experimental API. (array_from_fn #89379)
Expand description

Creates an array [T; N] where each fallible array element T is returned by the cb call. Unlike core::array::from_fn, where the element creation can’t fail, this version will return an error if any element creation was unsuccessful.

Arguments

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

Example

#![feature(array_from_fn)]

#[derive(Debug, PartialEq)]
enum SomeError {
    Foo,
}

let array = core::array::try_from_fn(|i| Ok::<_, SomeError>(i));
assert_eq!(array, Ok([0, 1, 2, 3, 4]));

let another_array = core::array::try_from_fn::<SomeError, _, (), 2>(|_| Err(SomeError::Foo));
assert_eq!(another_array, Err(SomeError::Foo));
Run