Deriving

Supported traits can be automatically implemented for your custom types, as follows:

  1. #[derive(Debug, Clone, Default)]
  2. struct Player {
  3.     name: String,
  4.     strength: u8,
  5.     hit_points: u8,
  6. }
  7. fn main() {
  8.     let p1 = Player::default(); // Default trait adds `default` constructor.
  9.     let mut p2 = p1.clone(); // Clone trait adds `clone` method.
  10.     p2.name = String::from("EldurScrollz");
  11.     // Debug trait adds support for printing with `{:?}`.
  12.     println!("{p1:?} vs. {p2:?}");
  13. }

This slide should take about 3 minutes.

Derivation is implemented with macros, and many crates provide useful derive macros to add useful functionality. For example, serde can derive serialization support for a struct using #[derive(Serialize)].