Skip to main content

builder

Macro builder 

Source
macro_rules! builder {
    (
        $(#[$attribute:meta])* $visibility:vis struct $name:ident
        $(<$($generic:tt $(: $bound:path)?),+ $(,)?>)?
        $(where $($shared:ident: $shared_bound:path),+ $(,)?)? {
            new($($(#[$required_into:ident $(= $required_doc:literal)?])* $required:ident: $required_type:ty),* $(,)?),
            $(
                $(#[$setter:ident $(= $field_doc:literal)?])* $field:ident
                : $type:ty = $value:expr
            ),* $(,)?
        }
    ) => { ... };
    (@emit [[$($attributes:tt)*] [$visibility:vis] $name:ident
        [$($generics:tt)*] [$($shared:ident: $shared_bound:path,)*]
        [$([$($required_into:ident)*] [$($required_doc:tt)*] $required:ident: $required_type:ty,)*]
        [$( ([$($setter:ident)*] [$($field_doc:tt)*] $field:ident [$type:ty] [$value:expr]) )*]] [$($arguments:tt)*]
    ) => { ... };
    (@type [doc $($rest:ident)*] $type:ty) => { ... };
    (@type [into $($rest:ident)*] $type:ty) => { ... };
    (@type [] $type:ty) => { ... };
    (@default $name:ident [$($generics:tt)*] [$($arguments:tt)*] [$($shared:ident: $shared_bound:path,)*];) => { ... };
    (@default $name:ident $generics:tt $arguments:tt $shared:tt;
        $required:ident $(, $rest:ident)*) => { ... };
}
Expand description

defines a builder struct with chainable setters

  • new(field: Type, ...) declares required constructor arguments
  • field: Type = value declares a field with a default and a setter
  • header and where bounds constrain the generated impls, never the struct
  • #[into] makes a constructor argument or setter accept impl Into<Type>
  • every field is public and has a setter, including constructor fields
  • an empty new() also generates Default
blit::builder! {
    pub struct Container<'a, T>
    where T: Copy,
    {
        new(elements: &'a [T]),
        #[into]
        border: Option<u8> = None,
        gap: u16 = 0,
    }
}
let container = Container::new(&[1, 2, 3])
    .gap(4)
    .border(1u8);