A derive macro asks Rust to generate implementations for eligible traits, reducing repetitive code while preserving the type’s standard behavior. For structs, Debug, Clone, and Default can be derived when every field implements the corresponding trait. section 4.5.3
Use derivation when:
- The generated implementation matches the desired behavior; write a manual implementation when customization is required. section 4.5.3
- All struct fields satisfy the selected trait bounds; otherwise automatic derivation cannot provide that implementation. section 4.5.3
- A declarative data model can drive an interface: clap uses derive and procedural macros to define CLI arguments and subcommands. section 10.3
Derive standard behavior
#[derive(Debug, Clone, Default)] struct DebuggableStruct { string: String, number: i32, } let value = DebuggableStruct::default(); println!("{:?}", value); println!("{:?}", value.clone()); The generated implementations support default construction, debug formatting, and cloning without handwritten trait code. section 4.5.3
#[derive(Debug, Clone, Default)]
struct DebuggableStruct {
string: String,
number: i32,
}
Inspect the compact struct declaration that derives Debug, Clone, and Default. section 4.5.3
Derive a command-line interface
#[derive(Parser)] struct Cli { url: hyper::Uri, #[command(subcommand)] command: Commands, } #[derive(Subcommand, Debug)] enum Commands { List, Create { body: String }, Read { id: i64 }, } clap turns these derived declarations into command parsing and help output, including positional arguments and subcommands. section 10.3
Listing 10.2 Top-level CLI definition for clap from src/main.rs
#[derive(Parser)] #1
struct Cli {
/// Base URL of API service #2
url: hyper::Uri, #3
#[command(subcommand)] #4
command: Commands, #5
}
Inspect a clap Parser derive with a URL positional argument and a subcommand field. section 10.3




