Learn Before
Code
Example of Derive Macro - Rust Programming
#![feature(proc_macro_hygiene)] use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; #[macro_use] extern crate quote; #[macro_use] extern crate syn; // Define the custom derive macro for the `HelloMacro` trait. macro_rules! hello_macro_derive { ($item:item) => { proc_macro::item(function! { // Parse the input tokens into a syntax tree. let ast = parse_macro_input!($item as DeriveInput); // Build the name of the type we want // to implement the trait for. let name = &ast.ident; // Generate the implementation of the `HelloMacro` trait. let gen = quote! { impl HelloMacro for #name { fn hello_macro(&self) { println!("Hello, Macro! My name is {}!", stringify!(#name)); } } }; // Return the generated implementation // as a `TokenStream`. gen.into() }) }; } // Define the `HelloMacro` trait. trait HelloMacro { fn hello_macro(&self); } // Define the `Person` struct and apply the custom derive macro. hello_macro_derive! { struct Person { name: String, } } fn main() { // Create an instance of the `Person` struct. let person = Person { name: String::from("Alice"), }; // Call the `hello_macro` method, which // is implemented via the custom derive macro. person.hello_macro(); }
0
1
Updated 2023-04-20
Tags
Object-Oriented Programming
Programming Language Paradigms
General programming languages
Computing Sciences