[][src]Attribute Macro macro_rules_attribute_proc_macro::macro_rules_attribute

#[macro_rules_attribute]

Applies the given macro_rules! macro to the decorated item.

This, as with any proc_macro_attribute, consumes the item it decorates: it is the macro_rules! macro job to generate it (it is thus able to modify it!).

For a version with "read-only" access to the item it decorates, see macro_rules_derive.

Example

Deriving getters for a (non-generic) struct:

#[macro_use]
extern crate macro_rules_attribute;

macro_rules! make_getters {(
    $(#[$struct_meta:meta])*
    $struct_vis:vis
    struct $StructName:ident {
        $(
            $(#[$field_meta:meta])*
            $field_vis:vis // this visibility will be applied to the getters instead
            $field_name:ident : $field_ty:ty
        ),* $(,)?
    }
) => (
    // First, generate the struct definition we have been given, but with
    // private fields instead.
    $(#[$struct_meta])*
    $struct_vis
    struct $StructName {
        $(
            $(#[$field_meta])*
            // notice the lack of visibility => private fields
            $field_name: $field_ty,
        )*
    }

    // Then, implement the getters:
    impl $StructName {
        $(
            #[inline]
            $field_vis
            fn $field_name (self: &'_ Self)
                -> &'_ $field_ty
            {
                &self.$field_name
            }
        )*
    }
)}

mod example {
    #[macro_rules_attribute(make_getters!)]
    /// The macro handles meta attributes such as docstrings
    pub
    struct Person {
        pub
        name: String,

        pub
        age: u8,
    }
}
use example::Person;

fn is_new_born (person: &'_ Person)
    -> bool
{
    // person.age == 0
    // ^ error[E0616]: field `age` of struct `example::Person` is private
    *person.age() == 0
}