Crates.io | static-dispatch |
lib.rs | static-dispatch |
version | 0.2.0 |
created_at | 2025-08-03 13:37:53.382304+00 |
updated_at | 2025-08-15 19:34:11.925822+00 |
description | Implement a trait for an enum, where all variants implement the trait |
homepage | |
repository | http://github.com/antonWetzel/static-dispatch |
max_upload_size | |
id | 1779724 |
size | 20,270 |
Derive a trait for an enum, where all variants implement the trait.
#[static_dispatch::dispatch]
trait ExampleBehavior {
fn as_value(self);
fn as_ref(&self) {}
fn as_mut(&mut self) {}
async fn async_fn(&self) {}
fn generic<T>(&self, value: T) {}
fn impl_arg(&self, value: impl Into<i32>) {}
}
struct A;
impl ExampleBehavior for A {
fn as_value(self) {}
// ...
}
struct B;
impl ExampleBehavior for B {
fn as_value(self) {}
// ...
}
#[static_dispatch::dispatch(ExampleBehavior)]
enum Example {
A(A),
B(B),
}
async fn example() {
for mut value in [
Example::A(A),
Example::B(B),
] {
value.as_mut();
value.as_ref();
value.async_fn().await;
value.generic(0);
value.generic(Some(0));
value.impl_arg(0i16);
value.impl_arg(0i32);
value.as_value();
}
}
static_dispatch::dispatch
macro_rules
static_dispatch::dispatch(macro_export)
to export the macrostatic_dispatch::dispatch(<TraitName>)
static_dispatch::dispatch(<crate>::<TraitName>)
for use with macro_export
no_std
support#[static_dispatch::dispatch]
trait SomethingBehavior<V> {
fn something(&self, value: V);
}
struct A<'a>(&'a i32);
impl<'a, V> SomethingBehavior<V> for A<'a> {
fn something(&self, _value: V) {}
}
struct B<T>(T);
impl<T, V> SomethingBehavior<V> for B<T> {
fn something(&self, _value: V) {}
}
#[static_dispatch::dispatch(impl<'a, T, V> SomethingBehavior<V> for Something<'a, T>)]
enum Something<'a, T> {
A(A<'a>),
B(B<T>),
}
#[test]
fn generic_example() {
let mut something = Something::A(A(&0));
something.something();
something = Something::B(B(0));
something.something();
}
self
, &self
or &mut self
impl
in return positionenum_dispatch
macro_rule
, not as a side effect in memory