pub trait Dispatch {
    type Output;

    // Required method
    fn dispatch(self) -> Self::Output;
}
Expand description

A dispatch of an object.

§Examples

#[derive(Debug, Default, PartialEq, Eq)]
struct Painting(Vec<usize>);
struct Stroke {
    thickness: usize,
}
impl Painting {
    fn draw(&mut self, stroke: Stroke) {
        self.0.push(2 * stroke.thickness)
    }
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Photoshop(Vec<usize>);
struct Filter {
    strength: usize,
}
impl Photoshop {
    fn draw(&mut self, filter: Filter) {
        self.0.push(5 * filter.strength)
    }
}

struct Dispatcher<T>(usize, PhantomData<T>);

impl Dispatch for Dispatcher<Painting> {
    type Output = Stroke;
    fn dispatch(self) -> Self::Output {
        Stroke { thickness: self.0 }
    }
}
impl Dispatch for Dispatcher<Photoshop> {
    type Output = Filter;
    fn dispatch(self) -> Self::Output {
        Filter { strength: self.0 }
    }
}

#[impl_dispatch({Painting; Photoshop})]
impl<A> Into<A> for Vec<usize> {
    fn into(self) -> A {
        let mut drawing = A::default();
        for num in self {
            drawing.draw(Dispatcher(num, PhantomData::<A>).dispatch());
        }
        drawing
    }
}

let painting: Painting = vec![1, 2, 3].into();
let photoshop: Photoshop = vec![1, 2, 3].into();
assert_eq!(painting, Painting(vec![2, 4, 6]));
assert_eq!(photoshop, Photoshop(vec![5, 10, 15]));

Required Associated Types§

source

type Output

The type of the output object.

Required Methods§

source

fn dispatch(self) -> Self::Output

Dispatches the object to a new object.

Implementors§