Avoiding boilerplate code for the builder pattern

This one is pretty straightforward. If you know about the builder pattern, you will know that it's a very useful pattern to create structures. We can avoid writing the whole new builder structure by using the derive_builder crate. So, let's add it to our Cargo.toml file and check how it works:

#[macro_use]extern crate derive_builder;use std::path::PathBuf;#[derive(Default, Debug, Builder)]#[builder(setter(into), default)]struct MyData {    field1: u8,    field2: PathBuf,    field3: String,}fn main() {    let data = MyDataBuilder::default()                .field2("path/to/file.png")                .field3("Some string")                .build().unwrap();    println!("{:?}", data);}

As you can see, we just added #[derive(Build)] to the structure and added ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.