Trait tuplez::MapperOnce

source ·
pub trait MapperOnce<T> {
    type Output;

    // Required method
    fn map_once(&mut self, value: T) -> Self::Output;
}
Expand description

Define functors for traversing the tuple by taking its elements.

To traverse a tuple with type Tuple<T0, T1, ... Tn>, you need to construct a custom functor type, which implements MapperOnce<T0>, MapperOnce<T1>MapperOnce<Tn>. Pass your functor to tuple’s foreach_once() method, then the tuple will call functor’s map_once() method in order of its elements and move its elements in.

§The mapper_once! macro

There is a mapper_once! macro that helps you build a functor simply, here is an example:

use tuplez::*;

let tup = tuple!(vec![1, 2, 3], "hello".to_string());
let tup2 = tup.foreach_once(mapper_once!{
    x: Vec<i32> => Box<[i32]> : x.into();
    x: String : x
});
// assert_eq!(tup, ... ); // No, `tup` has been moved
assert_eq!(
    tup2,
    tuple!(
        Box::<[i32; 3]>::new([1, 2, 3]) as Box<[i32]>,
        "hello".to_string()
    )
);

Check the documentation page of mapper_once! for detailed syntax.

§Custom functor

For more complex cases that cannot be covered by the mapper_once! macro, for example, you want to save some results inside your functor, you need to implement MapperOnce<Ti> for your functor for all element type Tis in tuples. Generic can be used.

For example:

use tuplez::*;

#[derive(Debug, Default)]
struct MyWrapper<T>(T);

struct Unwrapper;

impl<T: Default> MapperOnce<Option<T>> for Unwrapper {
    type Output = T;
    fn map_once(&mut self, value: Option<T>) -> Self::Output {
        value.unwrap_or_default()
    }
}

impl<T: Default, E> MapperOnce<Result<T, E>> for Unwrapper {
    type Output = T;
    fn map_once(&mut self, value: Result<T, E>) -> Self::Output {
        value.unwrap_or_default()
    }
}

impl<T: Default> MapperOnce<MyWrapper<T>> for Unwrapper {
    type Output = T;
    fn map_once(&mut self, value: MyWrapper<T>) -> Self::Output {
        value.0
    }
}

let tup = tuple!(
    Some([3.14, 9.8]),
    Result::<i32, ()>::Err(()),
    MyWrapper("hello".to_string())
);
let tup2 = tup.foreach_once(&mut Unwrapper);
// assert_eq!(tup, ... ); // No, `tup` has been moved
assert_eq!(tup2, tuple!([3.14, 9.8], 0, "hello".to_string()));

Required Associated Types§

source

type Output

Output type of mapping.

Required Methods§

source

fn map_once(&mut self, value: T) -> Self::Output

Take an element and map it to another value.

Implementors§