Trait type_dispatch::DispatchFn
source · pub trait DispatchFn {
type Output;
// Required method
fn dispatch_fn() -> Self::Output;
}
Expand description
A dispatch of a static function.
Prefer using the dispatch_fn
macro unless the dispatcher will
be used several times.
§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)
}
}
#[derive(Default)]
struct Dispatcher<T>(PhantomData<T>);
impl DispatchFn for Dispatcher<Painting> {
type Output = Stroke;
fn dispatch_fn() -> Self::Output {
Stroke { thickness: 5 }
}
}
impl DispatchFn for Dispatcher<Photoshop> {
type Output = Filter;
fn dispatch_fn() -> Self::Output {
Filter { strength: 3}
}
}
struct SingleStrokeMasterpiece;
#[impl_dispatch({Painting; Photoshop})]
impl<A> Into<A> for SingleStrokeMasterpiece {
fn into(self) -> A {
let mut drawing = A::default();
drawing.draw(Dispatcher::<A>::dispatch_fn());
drawing
}
}
let painting: Painting = SingleStrokeMasterpiece.into();
let photoshop: Photoshop = SingleStrokeMasterpiece.into();
assert_eq!(painting, Painting(vec![10]));
assert_eq!(photoshop, Photoshop(vec![15]));
Required Associated Types§
Required Methods§
sourcefn dispatch_fn() -> Self::Output
fn dispatch_fn() -> Self::Output
Dispatches a static function.
Object Safety§
This trait is not object safe.