Trait unarray::UnarrayArrayExt

source ·
pub trait UnarrayArrayExt<T, const N: usize> {
    // Required methods
    fn map_result<S, E>(
        self,
        f: impl FnMut(T) -> Result<S, E>,
    ) -> Result<[S; N], E>;
    fn map_option<S>(self, f: impl FnMut(T) -> Option<S>) -> Option<[S; N]>;
}
Expand description

An extension trait that adds methods to [T; N]

This trait provides UnarrayArrayExt::map_result and UnarrayArrayExt::map_option, which provide functionality similar to the nightly-only array::try_map

Required Methods§

source

fn map_result<S, E>(self, f: impl FnMut(T) -> Result<S, E>) -> Result<[S; N], E>

Maps an array, short-circuiting if any element produces an Err

let elements = ["123", "234", "345"];
let mapped = elements.map_result(|s| s.parse());
assert_eq!(mapped, Ok([123, 234, 345]));

This function applies f to every element. If any element produces an Err, the function immediately returns that error. Otherwise, it returns Ok(result) where result contains the mapped elements in an array.

This function does not allocate space on the heap

For functions that return an Option, consider using UnarrayArrayExt::map_option

source

fn map_option<S>(self, f: impl FnMut(T) -> Option<S>) -> Option<[S; N]>

Maps an array, short-circuiting if any element produces a None

fn parse(s: &str) -> Option<bool> {
  match s {
    "true" => Some(true),
    "false" => Some(false),
    _ => None,
  }
}

let elements = ["true", "false", "true"];
let mapped = elements.map_option(parse);
assert_eq!(mapped, Some([true, false, true]));

This function applies f to every element. If any element produces None, the function immediately returns None. Otherwise, it returns Some(result) where result contains the mapped elements in an array.

This function does not allocate space on the heap

For functions that return an Result, consider using UnarrayArrayExt::map_result

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<T, const N: usize> UnarrayArrayExt<T, N> for [T; N]

source§

fn map_result<S, E>(self, f: impl FnMut(T) -> Result<S, E>) -> Result<[S; N], E>

source§

fn map_option<S>(self, f: impl FnMut(T) -> Option<S>) -> Option<[S; N]>

Implementors§