rust-typed-builder icon indicating copy to clipboard operation
rust-typed-builder copied to clipboard

Add traits for matching on and transforming the generic parameter of the builder type

Open idanarye opened this issue 5 years ago • 0 comments

With #21 we want to convert all the builder type's generic parameters to a single tuple of types. Here we want to add traits for it.

Say we have:

#[derive(TypedStruct)]
pub struct Foo {
    pub bar: u32,
}

Our builder type will be (omitting the phantom field):

pub struct FooBuilder<F> {
    fields: F,
}

To allow extending the builder type in a forward-compatible way, we want to add the following traits:

trait FooBuilderWithBar {
    fn get(&self) -> u32;
}

trait FooBuilderWithoutBar {
    type With: FooBuilderWithBar;
    fn set(self, bar: u32) -> Self::With;
}

These traits will operate on F, not on FooBuilder<F>, and allow extending FooBuilder like so:

impl<F: FooBuilderWithoutBar> FooBuilder<F> {
    pub fn bar_as_42(self) -> <F as FooBuilderWithoutBar>::With {
        Foo {
	    fields: FooBuilderWithoutBar::set(self, 42),
	}
    }
}

idanarye avatar Dec 12 '19 14:12 idanarye