How to Write a Custom Serde Derive

Create a procedural macro crate using syn and quote to generate Serde serialization code for your structs.

You write a custom Serde derive by creating a procedural macro crate that implements the proc_macro::TokenStream interface and uses syn to parse input and quote to generate Serde-compatible code.

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Serialize)]
pub fn derive_serialize(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let expanded = quote! {
        impl serde::Serialize for #name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where S: serde::Serializer {
                serializer.serialize_str("placeholder")
            }
        }
    };
    TokenStream::from(expanded)
}
  1. Create a new crate with --lib and add proc-macro = true to Cargo.toml.
  2. Add syn and quote as dependencies in Cargo.toml.
  3. Define a #[proc_macro_derive] function that parses the input struct and returns generated code.
  4. Use #[derive(Serialize)] on your struct in the consuming crate to trigger the macro.