If you’re new to Rust, you may have seen #[derive(...)]
sitting above structs or enums and thought:
“What does that even mean?”
Let’s break it down step by step.
What is #[derive(...)]
?
At its core, #[derive(...)]
is a compiler instruction (attribute).
When you attach it to your type (a struct
or enum
), you are telling Rust:
“Hey compiler, please generate some extra abilities for this type automatically, so I don’t have to write all the boring code myself.”
Why do we need it?
In Rust, if you want a type to be:
Printable → so you can see its contents with
println!
,Comparable → so you can check if two values are equal with
==
,Cloneable → so you can copy it,
…you’d normally have to write all the supporting code yourself.
That’s repetitive, and it breaks the DRY (Don’t Repeat Yourself) principle.
Rust solves this with #[derive(...)]
.
Commonly Derived Abilities
Here are some of the most common things you can ask the compiler to generate:
Debug
→ “Give me the ability to print this type withprintln!(”{:?}”, value)
.”Clone
→ “Give me the ability to make a duplicate with.clone()
.”PartialEq
→ “Give me the ability to compare two values with==
.”
And these are all provided by Rust’s standard library, so you don’t have to reinvent the wheel.
Example Without Derive
Here, we had to manually write a method just to compare two Point
s.
Example With Derive
With a single line, we told Rust to auto-generate printing, cloning, and comparison for us.
TL;DR
#[derive(...)]
is like asking Rust:
“Give this type some standard abilities (like printing, copying, comparing) without me having to spell out all the code.”
It saves time, reduces bugs, and keeps your code clean.
Sincerely I write literary fiction books. But your topic interest me. I once tried coding on termux buh it was a disaster