Trait tuplez::MapperMut

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

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

Define functors for traversing the tuple by mutable references to tuple’s elements.

To traverse a tuple with type Tuple<T0, T1, ... Tn>, you need to construct a custom functor type, which implements MapperMut<T0>, MapperMut<T1>MapperMut<Tn>. Pass your functor to tuple’s foreach_mut() method, then the tuple will call functor’s map_mut() method in order of its elements and pass in the mutable reference of the element.

§The mapper_mut! macro

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

use tuplez::*;

let mut tup = tuple!(2, "hello", 3.14);
let tup2 = tup.foreach_mut(mapper_mut!{
    x: i32: { (*x) *= (*x); *x - 1 };
    x: f32 => (): *x += 1.0;
    x, 'a: &'a str: *x
});
assert_eq!(tup, tuple!(4, "hello", 3.14 + 1.0));
assert_eq!(tup2, tuple!(3, "hello", ()));

Check the documentation page of mapper_mut! for detailed syntax.

§Custom functor

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

For example:

use tuplez::*;

#[derive(PartialEq, Eq, Debug)]
struct MyNonDefault(i32);

#[derive(Default)]
struct TakeValue {
    is_my_struct: Vec<bool>,
}

impl<T: Default> MapperMut<T> for TakeValue {
    type Output = T;
    fn map_mut(&mut self, value: &mut T) -> Self::Output {
        self.is_my_struct.push(false);
        std::mem::take(value)
    }
}

impl MapperMut<MyNonDefault> for TakeValue {
    type Output = i32;
    fn map_mut(&mut self, value: &mut MyNonDefault) -> Self::Output {
        self.is_my_struct.push(true);
        std::mem::take(&mut value.0)
    }
}

let mut take_value = TakeValue::default();
let mut tup = tuple!(3.14, "hello".to_string(), MyNonDefault(14));
let tup2 = tup.foreach_mut(&mut take_value);
assert_eq!(take_value.is_my_struct, vec![false, false, true]);
assert_eq!(tup, tuple!(0.0, String::new(), MyNonDefault(0)));
assert_eq!(tup2, tuple!(3.14, "hello".to_string(), 14));

Required Associated Types§

source

type Output

Output type of mapping.

Required Methods§

source

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

Map an element to another value through its immutable reference.

Implementors§