Attribute Macro macro_rules_derive
#[macro_rules_derive]
Expand description
Applies the given macro_rules!
macro to the decorated item.
This, as with any #[derive(...)]
, does not consume the item it
decorates: instead, it only generates code on top of it.
§Examples
§Implementing Into<Int>
for a given #[repr(Int)]
enum
:
#[macro_use]
extern crate macro_rules_attribute;
macro_rules! ToInteger {(
#[repr($Int:ident)]
$(#[$enum_meta:meta])*
$pub:vis
enum $Enum:ident {
$(
$Variant:ident $(= $value:expr)?
),* $(,)?
}
) => (
impl ::core::convert::From<$Enum> for $Int {
#[inline]
fn from (x: $Enum)
-> Self
{
x as _
}
}
)}
#[macro_rules_derive(ToInteger)] // or `#[macro_rules_derive(ToInteger!)]`
#[repr(u32)]
enum Bool {
False,
True,
}
fn main ()
{
assert_eq!(u32::from(Bool::False), 0);
assert_eq!(u32::from(Bool::True), 1);
// assert_eq!(u8::from(Bool::False), 0);
// ^ error[E0277]: the trait bound `u8: std::convert::From<main::Bool>` is not satisfied
}
§Difference with #[derive]
#[macro_rules_derive]
is specifically intended to be used
with macro_rules!
-based derives:
-
it won’t accept classic derives;
-
thanks to that, the trailing
!
on the macro name is not mandatory.
For #[derive]
, it’s exactly the opposite.