Use #[derive()]

Source: https://doc.rust-lang.org/rust-by-example/trait/derive.html

Rust has a feature called attributes and you use #[] to annotate attributes you want to use. There are many useful attributes and one is called derive. It automatically adds trait implementation for traits that implement derive macros.

For example, the following code automatically implements the Debug trait, so you can use the debug formatter.

#[derive(Debug)]
struct Ex {
    field1: i32,
    field2: i64,
}

fn main() {
    let ex = Ex { field1: 32, field2: 64 };
    println!("{:?}", ex);
}

There are other useful traits to derive.

  • Clone provide clone().
  • Debug makes your custom type (e.g., struct or enum) printable.
  • Default creates a default instance for your custom type (e.g., struct or enum) with empty values.
  • Hash computes a hash.