The derive attribute can be used to auto-implement certain Traits for you.
Some traits you can most likely derive:
- std::default::Default
- serde’s Serialize & Deserialize (Requires
derive
feature on serde) - std::clone::Clone
- std::fmt::Debug
To use derive in a simple example:
// We'll use std::fmt::Debug and std::default::Default traits
#[derive(Debug, Default)]
struct Point (u32, u32); // Simple Point structure
fn main() {
// We call the default method (Provided for us by Default)
let p: Point = Point::default(); // This is equal to 'let p: Point = Point(0, 0);'
// We can debug print out the structure (Provided by Debug)
// Note: Using '{}' will fail as we don't implement std::fmt::Display
// Debug uses '{:?}' and will print the structure (structure name, and fields + values)
// This also means any values we use must also implement Debug and Default!
println!("p = {:?}", p);
// p = Point(0, 0)
}