Function try_map

Source
pub fn try_map<T, const N: usize, F, R>(
    vals: [T; N],
    f: F,
) -> <<R as Try>::Residual as Residual<[<R as Try>::Output; N]>>::TryType
where F: FnMut(T) -> R, R: Try, <R as Try>::Residual: Residual<[<R as Try>::Output; N]>,
Expand description

A fallible function f applied to each element on array self in order to return an array the same size as self or the first error encountered.

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>. If you return Option<T> from the closure, you’ll get an Option<[T; N]>.

§Examples

let a = ["1", "2", "3"];
let b = array_util::try_map(a, |v| v.parse::<u32>()).unwrap().map(|v| v + 1);
assert_eq!(b, [2, 3, 4]);

let a = ["1", "2a", "3"];
let b = array_util::try_map(a, |v| v.parse::<u32>());
assert!(b.is_err());

use std::num::NonZeroU32;
let z = [1, 2, 0, 3, 4];
assert_eq!(array_util::try_map(z, NonZeroU32::new), None);
let a = [1, 2, 3];
let b = array_util::try_map(a, NonZeroU32::new);
let c = b.map(|x| x.map(NonZeroU32::get));
assert_eq!(c, Some(a));