Attribute Macro substrate::type_dispatch::impl_dispatch
source · #[impl_dispatch]
Expand description
Dispatches a trait implementation to a specified set of generic types.
§Syntax
Sets are delimited with curly braces ({}
) and have semicolon-separated elements. Sets
are used to enumerate types to be assigned to a generic argument or set of generic arguments.
Comma-separated elements are combined using a cartesian product, making it easier to implement traits on any combination of the provided types.
§Semantics
The supplied dispatch types are dispatched starting from the first generic type argument of the trait implementation.
§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
}
}
let x: usize = GenericStruct(1u64, 3u32).into();
assert_eq!(x, 4);
let x: u64 = GenericStruct(1u64, 3u8).into();
assert_eq!(x, 4);
let x: usize = GenericStruct(1u16, 3u32).into();
assert_eq!(x, 4);
let x: u64 = GenericStruct(1u16, 3u8).into();
assert_eq!(x, 4);
// The following two lines will not compile as `GenericStruct` does not implement
// these particular type combinations:
// ```
// let x: u64 = GenericStruct(1u64, 3u32).into();
// let x: usize = GenericStruct(1u64, 3u8).into();
// ```