Trait ArrayExt

Source
pub trait ArrayExt<T, const N: usize> {
    // Required methods
    fn try_map<F, U, E>(self, f: F) -> Result<[U; N], E>
       where F: FnMut(T) -> Result<U, E>;
    fn map2<F, U>(self, f: F) -> [U; N]
       where F: FnMut(T) -> U;
}
Expand description

Extension of [T; N] to add methods

Required Methods§

Source

fn try_map<F, U, E>(self, f: F) -> Result<[U; N], E>
where F: FnMut(T) -> Result<U, E>,

Fallible version of map. The provided function will be run on every element until the array ends or an error is returned.

§Errors

If f returns an Err, that error will be returned by this function. The already initialized elements will be dropped when an error occurs. The new array will be returned if no error occurs.

§Panics

This function panics if f panics. The already initialized elements will be dropped when a panic occurs.

§Examples
let x: [u32; 3] = [1, 2, 3];
let y = x.try_map(|v| v.checked_add(1).ok_or("overflow"));
assert_eq!(y, Ok([2, 3, 4]));

let x = [1, 2, 3, u32::MAX];
let y = x.try_map(|v| v.checked_add(1).ok_or("overflow"));
assert_eq!(y, Err("overflow"));
Source

fn map2<F, U>(self, f: F) -> [U; N]
where F: FnMut(T) -> U,

Example of how map could be reimplemented in terms of try_map.

§Panics

This function panics if f panics. The already initialized elements will be dropped when a panic occurs.

§Examples
let x = [1, 2, 3];
let y = x.map2(|v| v + 1);
assert_eq!(y, [2, 3, 4]);

let x = [1, 2, 3];
let mut temp = 0;
let y = x.map2(|v| { temp += 1; v * temp });
assert_eq!(y, [1, 4, 9]);

let x = ["Ferris", "Bueller's", "Day", "Off"];
let y = x.map2(|v| v.len());
assert_eq!(y, [6, 9, 3, 3]);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

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

Source§

fn try_map<F, U, E>(self, f: F) -> Result<[U; N], E>
where F: FnMut(T) -> Result<U, E>,

Source§

fn map2<F, U>(self, f: F) -> [U; N]
where F: FnMut(T) -> U,

Implementors§