Macro sketchbook::compose
source · [−]macro_rules! compose {
{
$(#[$($meta_code:tt)*])?
$v:vis struct $name:ident {
$(
$(#[$attr:ident])? $vi:vis $field:ident: $field_type:ty
),*$(,)?
}
} => { ... };
{
$(#[$($meta_code:tt)*])?
$v:vis enum $name:ident {
$($(#[$attr:ident])? $variant:ident$(($variant_type:ty))?),*$(,)?
}
} => { ... };
}
Expand description
Create type composed of other types.
For structs, this macro is used in the following way.
When the #[part]
attribute is applied to a field, that field will be available using
AsPart<T>
. Only one field can have a #[part]
of a particular type.
compose! {
struct Test {
a: i32,
#[part]
b: i32,
#[part]
c: f32,
}
}
let x = Test { a: 123, b: 456, c: 1.23 };
let y: &f32 = x.as_part();
assert_eq!(y, &1.23);
For enums, this macro is used in the following way.
When the #[part]
attribute is applied to a variant, that variant will be available using
TryAsPart<T>
. Only one variant can have a #[part]
of a particular type. Additionally, the
variant must be a tuple of a single value.
compose! {
enum Test {
A,
#[part]
B(i32),
#[part]
C(f32),
}
}
let x = Test::B(123);
let y: Option<&i32> = x.try_as_part();
assert_eq!(y, Some(&123));