liveBook · Manning

Default

As explained in Write Powerful Rust Macros

Default is the standard Rust trait for constructing a default value of a type.

Default is the Rust trait for constructing a fallback value of a type. Implementing it defines that type’s default value. Common built-in defaults include 0 for numbers, an empty String, false for Booleans, and None for Option. section 8.3

A builder can use Default instead of panicking when a field is missing. With a builder_defaults attribute, generated code calls unwrap_or_default(); without it, generated code retains an expect-based missing-field failure. section 8.3

Using defaults in a builder

A derived builder can fill omitted fields when the attribute is present: #[derive(Builder)] #[builder_defaults] struct ExampleStructTwoFields { string_value: String, int_value: i32, } let example = ExampleStructTwoFields::builder().build(); assert_eq!(example.string_value, String::default()); assert_eq!(example.int_value, Default::default());

Default-based generated code has two important constraints:

  • A procedural macro can improve that diagnostic by generating field-specific where clauses with core::default::Default and applying the offending type’s span. section 8.4

How Write Powerful Rust Macros covers it

How deep it goes
Explains trait usage, generated unwrap_or_default calls, and field-specific diagnostics, but does not develop custom Default implementations.
Examples
Demonstrates defaulted String and integer fields, a non-Default field failure, and generated quote_spanned assertions.
What it assumes
Assumes familiarity with Rust builders, derive macros, attributes, and procedural-macro code; establishes built-in defaults through examples.
What you can do after
Apply it via Rust builders and generated code to supply fallback values and enforce Default bounds at compilation.
How it connects
Connects Default with builder patterns, procedural macros, derive macros, attributes, Option, compiler diagnostics, and source spans.

Also explained in

Compare how 2 books explain Default →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.