rust / beginner
Snippet
Derive Macros for Automatic Trait Implementation
Rust's derive system auto-generates implementations of common traits. #[derive(...)] attaches to structs and instructs the compiler to produce Debug for printing, Clone for duplication, PartialEq for equality comparison, and Default for a constructor that sets all fields to their zero values. This eliminates boilerplate while keeping the logic explicit and predictable.
snippet.rs
1
#[derive(Debug, Clone, PartialEq, Default)]\nstruct Config {\n username: String,\n max_retries: u32,\n enabled: bool,\n}\n\nfn main() {\n let default_config = Config::default();\n println!("Default: {:?}", default_config);\n \n let custom = Config {\n username: String::from("admin"),\n max_retries: 3,\n enabled: true,\n };\n \n let cloned = custom.clone();\n println!("Cloned: {:?}", cloned);\n println!("Equal: {}", custom == cloned);\n}
Breakdown
1
#[derive(Debug, Clone, PartialEq, Default)]
Macro attribute that expands to trait implementations at compile time
2
Config::default()
Default sets username to "", max_retries to 0, enabled to false
3
String::from("admin")
Creates a String from a string literal for the username field
4
custom.clone()
Clone trait provides deep copy — both structs exist independently
5
custom == cloned
PartialEq trait enables == operator comparison between structs