try_init_slice

Function try_init_slice 

Source
pub fn try_init_slice<T, E, F: FnMut(usize) -> Result<T, E>>(
    s: &mut [MaybeUninit<T>],
    f: F,
) -> Result<&mut [T], E>
Expand description

Try to initialize all the elements in a slice, returning early if it fails.

For each item in the slice, the given function will be called with the items index and the result be written into the slice. If the initialization of any item fails, all previously initialized items will be dropped, meaning that the entire slice will be uninitialized again, and the error returned by f will be returned from the function.

ยงExamples

#![feature(maybe_uninit_uninit_array)]
use init_array::try_init_slice;
use core::mem::MaybeUninit;

let mut arr = MaybeUninit::uninit_array::<5>();

assert_eq!(try_init_slice::<usize, usize, _>(&mut arr, |i| Ok(i)), Ok([0, 1, 2, 3, 4].as_mut_slice()));
assert_eq!(try_init_slice::<usize, usize, _>(&mut arr, |i| Err(i)), Err(0));