What are derive macros and which common ones does Rust provide?
Answer
Derive macros (using #[derive(...)]) automatically generate trait implementations for a type based on its structure, eliminating manual boilerplate. The Rust standard library provides these commonly-derived traits: Debug (enables {:?} formatting for debugging), Clone (enables .clone() for deep copies), Copy (marks types that are bit-copyable — requires Clone), PartialEq and Eq (enables == and != comparisons), PartialOrd and Ord (enables ordering), Hash (enables use as HashMap key). Third-party derives are ubiquitous: serde::Serialize/Deserialize (JSON, etc.), thiserror::Error, and clap::Parser for CLI arguments.
Previous
What is the difference between procedural macros and declarative macros in Rust?
Next
What is Serde and how is it used in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?