builder_def

Macro builder_def 

Source
macro_rules! builder_def {
    (
        $(#[$struct_meta:meta])*
        $vis:vis struct $name:ident + $builder:ident {
            $(
                $(#[$field_meta:meta])*
                $field_vis:vis $field:ident : $field_ty:ty $(= $default:expr)?
            ),* $(,)?
        }
    ) => { ... };
    (@default $default:expr) => { ... };
    (@default) => { ... };
    (@unwrap $value:expr, $struct:expr, $field:expr, $ty:ty, $default:expr) => { ... };
    (@unwrap $value:expr, $struct:expr, $field:expr, Option<$inner:ty>,) => { ... };
    (@unwrap $value:expr, $struct:expr, $field:expr, $ty:ty,) => { ... };
}
Expand description

Generates a builder struct and basic setter methods.

§Example

builder_def! {
    /// Documentation for the target struct
    #[derive(Clone, Copy, Debug)]
    pub struct Field + FieldBuilder {
        /// Required field - panics if not set
        pub name: &'static str,
        /// Optional field - defaults to None
        pub rename: Option<&'static str>,
        /// Field with default value
        pub flags: FieldFlags = FieldFlags::empty(),
    }
}

// Then add custom constructors/methods manually:
impl FieldBuilder {
    pub const fn new(name: &'static str, shape: &'static Shape, offset: usize) -> Self {
        Self::default()
            .name(name)
            .shape(ShapeRef::Static(shape))
            .offset(offset)
    }
}

This generates:

  • The struct as written (with defaults applied)
  • TargetBuilder struct with Option<T> for each field
  • TargetBuilder::default() (all fields None, except those with defaults)
  • Setter methods for each field
  • TargetBuilder::build() -> Target (panics if required fields not set)

Field types:

  • field: T - Required, panics if not set
  • field: Option<T> - Optional, defaults to None
  • field: T = expr - Has default value, uses expr if not set