Custom Derive
In Rust, you’ve always been able to automatically implement some traitsthrough the derive attribute:
#![allow(unused_variables)]
fn main() {
#[derive(Debug)]
struct Pet {
name: String,
}
}
The Debug
trait is then implemented for Pet
, with vastly less boilerplate. For example, without derive
, you'd haveto write this:
#![allow(unused_variables)]
fn main() {
use std::fmt;
struct Pet {
name: String,
}
impl fmt::Debug for Pet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Pet { name } => {
let mut debug_trait_builder = f.debug_struct("Pet");
let _ = debug_trait_builder.field("name", name);
debug_trait_builder.finish()
}
}
}
}
}
Whew!
However, this only worked for traits provided as part of the standardlibrary; it was not customizable. But now, you can tell Rust what to do whensomeone wants to derive your trait. This is used heavily in popular crateslike serde and Diesel.
For more, including learning how to build your own custom derive, see TheRust ProgrammingLanguage.