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)
}
- Create a new crate with
--liband addproc-macro = truetoCargo.toml. - Add
synandquoteas dependencies inCargo.toml. - Define a
#[proc_macro_derive]function that parses the input struct and returns generated code. - Use
#[derive(Serialize)]on your struct in the consuming crate to trigger the macro.