Real-World Problem: The Creeping Burden of Boilerplate Code
Repetitive trait implementations hit almost every growing Rust codebase. Picture a system with 50 domain models, database entities, and API payloads. For audit logs, telemetry events, or compliance checks, every struct must describe its fields at runtime—often by dumping values into key-value pairs or building a structured summary dictionary.
Writing this by hand looks harmless enough when you only have two models:
pub trait DescribeModel {
fn describe(&self) -> Vec<(&'static str, String)>;
}
struct UserProfile {
username: String,
email: String,
sign_in_count: u32,
}
impl DescribeModel for UserProfile {
fn describe(&self) -> Vec<(&'static str, String)> {
vec![
("username", self.username.clone()),
("email", self.email.clone()),
("sign_in_count", self.sign_in_count.to_string()),
]
}
}
Fast-forward six months. The project now holds 80 structs spanning 12,000 lines of business logic. A developer adds a phone_number field to UserProfile, forgets to touch describe(), and the pull request slips through code review. Tests still pass. While Rust allows you to eliminate runtime bugs at compile time for state logic, it cannot automatically verify that a manually assembled list of string literals matches your struct layout. When downstream telemetry breaks silently in staging, engineers spend hours auditing dozens of nearly identical implementations across the repository.
Root Cause Analysis: Why Manual Abstractions Fall Apart
Rust deliberately omits runtime reflection. Unlike Java’s Class.getDeclaredFields(), Go’s reflect package, or .NET reflection (where modern teams use compile-time code generation via C# source generators), Rust strips field names and struct layouts during compilation to guarantee zero-cost abstractions, predictable memory layouts, and leak-free execution without a garbage collector.
Because the compiled binary keeps zero runtime type metadata, any introspection requires registration ahead of time. Relying on hand-written traits creates three distinct hazards:
- Information redundancy: You define field names once in the struct and duplicate them in the trait block.
- Silent schema drift: Adding, renaming, or removing fields never triggers compiler errors in separate trait code.
- Refactoring overhead: Simple schema migrations turn into tedious, error-prone find-and-replace churn across dozens of files.
We need compile-time metaprogramming. While modern systems languages like Zig rely on comptime for type introspection, Rust delegates this to macro expansion. The compiler should inspect struct tokens during compilation and generate the required trait logic on the fly.
Solutions Compared: Choosing the Right Automation Strategy
Rust teams generally evaluate three paths to tackle this duplication:
1. Declarative Macros (macro_rules!)
Declarative macros rely on syntactic pattern matching. They work well for small helper wrappers, but they struggle with arbitrary struct definitions.
- Pros: Built directly into
rustc; zero extra dependencies; near-instant compilation. - Cons: Cannot inspect structs defined elsewhere in your codebase; difficult to combine with custom helper attributes; complex matches become unreadable fast.
2. Code Generation via build.rs
Another option runs a custom build.rs script or external code generator. It reads schema specifications (such as Protobuf definitions or JSON Schema contracts) and emits .rs source files into OUT_DIR.
- Pros: Language-agnostic; clean fit when sharing contracts across Python, Go, and Rust services.
- Cons: Obscures IDE type hints and autocompletion; introduces external tooling dependencies; adds friction to everyday local development loops.
3. Procedural Derive Macros (syn + quote)
A procedural derive macro lets you annotate any struct with #[derive(DescribeModel)]. During compilation, rustc hands the struct’s Abstract Syntax Tree (AST) to your macro crate as a stream of tokens. Your macro transforms those tokens and appends the generated trait implementation straight back into the compiler pipeline.
- Pros: Clean call site (just add
#[derive(...)]); fully type-checked; produces immediate compiler errors with accurate source spans if types mismatch. - Cons: Requires a dedicated proc-macro crate; adds roughly 2 to 4 seconds to the first cold build due to compiling parsing dependencies like
syn.
Best Approach: Building a Custom Derive Macro with syn and quote
For scalable maintainability, procedural derive macros offer the cleanest ergonomics. We will use syn to parse raw token streams into structured syntax trees and quote to assemble those nodes back into Rust code.
Step 1: Setting Up the Workspace
Rust requires procedural macros to live inside their own library crate with proc-macro = true enabled. Set up a cargo workspace so our macro and test consumer live side by side:
mkdir derive_demo && cd derive_demo
cargo new --lib describe_derive
cargo new describe_consumer
In the root Cargo.toml, link both crates:
[workspace]
members = ["describe_derive", "describe_consumer"]
Configure describe_derive/Cargo.toml to declare the crate as a procedural macro and pull in the parsing ecosystem:
[package]
name = "describe_derive"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2.0", features = ["extra-traits"] }
quote = "1.0"
proc-macro2 = "1.0"
Step 2: Defining the Procedural Macro Entrypoint
Open describe_derive/src/lib.rs. Procedural derive macros require an entrypoint function marked with #[proc_macro_derive(TraitName)]. This entrypoint accepts a compiler token stream and returns a new token stream containing the generated code.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(DescribeModel)]
pub fn describe_model_derive(input: TokenStream) -> TokenStream {
// Parse compiler tokens into an AST representation
let ast = parse_macro_input!(input as DeriveInput);
// Generate the trait implementation
let expanded = impl_describe_model(&ast);
// Return the generated tokens to the compiler
TokenStream::from(expanded)
}
Step 3: Traversing the AST and Emitting Code with quote
Next, implement the AST inspection in describe_derive/src/lib.rs. The macro needs to verify that the target is a struct with named fields, iterate over each field identifier, and generate a descriptive tuple.
use syn::{Data, Fields};
fn impl_describe_model(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
let name = &ast.ident;
// Restrict derivation exclusively to structs with named fields
let fields = match &ast.data {
Data::Struct(data_struct) => match &data_struct.fields {
Fields::Named(fields_named) => &fields_named.named,
_ => {
return syn::Error::new_spanned(
ast,
"DescribeModel only supports structs with named fields, not tuple or unit structs",
)
.to_compile_error();
}
},
_ => {
return syn::Error::new_spanned(
ast,
"DescribeModel can only be derived on structs, not enums or unions",
)
.to_compile_error();
}
};
// Generate a tuple expression for each individual field
let field_descriptions = fields.iter().map(|f| {
let field_ident = f.ident.as_ref().unwrap();
let field_name_str = field_ident.to_string();
quote! {
(#field_name_str, format!("{:?}", self.#field_ident))
}
});
// Synthesize the complete trait implementation block
quote! {
impl DescribeModel for #name {
fn describe(&self) -> Vec<(&'static str, String)> {
vec![
#(#field_descriptions),*
]
}
}
}
}
The expression #(#field_descriptions),* uses quote‘s built-in repetition syntax. Much like repetition in macro_rules!, it expands the iterator into comma-separated token sequences inside the vec![] literal.
Step 4: Consuming the Custom Derive Macro
Add the derive crate as a dependency in describe_consumer/Cargo.toml:
[package]
name = "describe_consumer"
version = "0.1.0"
edition = "2021"
[dependencies]
describe_derive = { path = "../describe_derive" }
Now declare the trait and test your custom derive macro inside describe_consumer/src/main.rs:
use describe_derive::DescribeModel;
pub trait DescribeModel {
fn describe(&self) -> Vec<(&'static str, String)>;
}
#[derive(Debug, DescribeModel)]
struct OrderPayload {
order_id: u64,
customer_ref: String,
is_completed: bool,
}
#[derive(Debug, DescribeModel)]
struct ServerConfig {
host: String,
port: u16,
}
fn main() {
let order = OrderPayload {
order_id: 94821,
customer_ref: String::from("ACME-CORP"),
is_completed: false,
};
let config = ServerConfig {
host: String::from("127.0.0.1"),
port: 8080,
};
println!("--- Order Description ---");
for (field, value) in order.describe() {
println!("{field}: {value}");
}
println!("\n--- Config Description ---");
for (field, value) in config.describe() {
println!("{field}: {value}");
}
}
Run the consumer application:
cargo run -p describe_consumer
The binary executes and outputs your field data directly:
--- Order Description ---
order_id: 94821
customer_ref: "ACME-CORP"
is_completed: false
--- Config Description ---
host: "127.0.0.1"
port: 8080
Any new field added to OrderPayload or ServerConfig appears in describe() immediately on your next build. If someone derives DescribeModel on an enum, the macro emits a clear compiler error at that exact source location pointing out the invalid usage. Offloading repetitive trait code to syn and quote keeps domain models lean, clean, and guaranteed to match schema updates across every build.

