Skip to main content

array_try_from_fn

Function array_try_from_fn 

Source
pub fn array_try_from_fn<E, T, const N: usize>(
    cb: impl FnMut(usize) -> Result<T, E>,
) -> Result<[T; N], E>
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.

The return type of this function depends on the return type of the closure. If you return Result<T, E> from the closure, you’ll get a Result<[T; N], E>.

Note: Unlike the unstable core implementation this function only supports a closure returning a Result.

§Arguments

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

§Example

use wasmtime_internal_core::array::array_try_from_fn;

let array: Result<[u8; 5], _> = array_try_from_fn(|i| i.try_into());
assert_eq!(array, Ok([0, 1, 2, 3, 4]));

let array: Result<[i8; 200], _> = array_try_from_fn(|i| i.try_into());
assert!(array.is_err());