Macro substrate::type_dispatch::dispatch_fn
source · dispatch_fn!() { /* proc-macro */ }
Expand description
Dispatches a function body based on a given generic type.
§Syntax
The syntax is effectively the same as a match statement, but the patterns are instead simply comma-separated lists of types.
§Semantics
Unlike normal match statements, duplicate arms are not allowed. Only the constant corresponding to the unique matching arm will be dispatched.
dispatch_fn!
internally uses the DispatchFn
trait to dispatch functions,
meaning that types do not have to match exactly (i.e. impl_dispatch
might have
std::vec::Vec
while the dispatch_const!
arm has Vec
).
§Examples
struct GenericStruct<A, B>(A, B);
// Creates 4 trait implementations.
#[impl_dispatch({u64; u16}, {u32, usize; u8, u64})]
impl<A, B, C> Into<C> for GenericStruct<A, B> {
fn into(self) -> C {
self.0 as C + self.1 as C + dispatch_fn!(
match A, B {
u64, u32 => vec![()]: Vec<()>,
u64, u8 => vec![1, 2]: Vec<u32>,
u16, u32 => "ABC".to_string(): String,
u16, u8 => "ABCD": &'static str,
}
).len() as C
}
}
let x: usize = GenericStruct(1u64, 3u32).into();
assert_eq!(x, 5);
let x: u64 = GenericStruct(1u64, 3u8).into();
assert_eq!(x, 6);
let x: usize = GenericStruct(1u16, 3u32).into();
assert_eq!(x, 7);
let x: u64 = GenericStruct(1u16, 3u8).into();
assert_eq!(x, 8);