When derive_builder expands, it generates a builder struct and an associated error enum.
Builder Struct:
- Inherits visibility, generics, and attributes from the target struct.
- Implements
Default (if impl_default is true) by calling the inherent create_empty method. - Includes an inherent method (default name
create_empty) that initializes all fields to None or PhantomData. - Can automatically derive additional traits (like
Clone) via the derives configuration.
Error Enum:
- Named
{TargetStruct}Error. - Contains
UninitializedField(&'static str) to indicate which field was missing during .build(). - Contains
ValidationError(String) if generate_validation_error is enabled. - Implements
std::error::Error if the std feature is enabled.
// Conceptual expansion of a builder
#[derive(Clone)]
pub struct FooBuilder {
foo: u32,
}
#[doc="Error type for FooBuilder"]
#[derive(Debug)]
#[non_exhaustive]
pub enum FooBuilderError {
/// Uninitialized field
UninitializedField(&'static str),
/// Custom validation error
ValidationError(::derive_builder::export::core::string::String),
}
impl FooBuilder {
fn create_empty() -> Self {
Self { foo: Default::default() }
}
}
impl Default for FooBuilder {
fn default() -> Self {
Self::create_empty()
}
}