Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Derive Macros

#![allow(unused)]
fn main() {
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(MyTrait)]
pub fn my_trait(input: TokenStream) -> TokenStream
{
  let input = parse_macro_input!(input as DeriveInput);
  let name = input.ident;
  
  // Split a type’s generics into the pieces required for impl’ing a trait for that type.
  let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

  let out = quote! {
    impl #impl_generics MyTrait for #name #ty_generics #where_clause
    {
    }
  };
  out.into()
}
}
#![allow(unused)]
fn main() {
trait MyTrait
{}
}
#![allow(unused)]
fn main() {
#[derive(MyTrait)]
struct MyStruct {}
}