Skip to content

Conversation

Techassi
Copy link
Contributor

Fixes #67

This PR adds support for the PostBuild trait, which allows users to perform custom validation when the .build() method is called. The validation runs as the last step of the build method.

An example:

use typed_builder::{PostBuild, TypedBuilder};

#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(postbuild)]
struct Foo {
    x: i32,
    y: i32,
}

impl PostBuild for Foo {
    type Output = Result<Self, String>;

    fn postbuild(self) -> Self::Output {
        if self.x >= 5 {
            return Err("x too high - must be below or 5".into());
        }

        Ok(self)
    }
}

fn main() {
    let foo = Foo::builder().x(1).y(2).build().unwrap();
    assert_eq!(foo, Foo { x: 1, y: 2 });

    // Fails to validate during runtime
    // let foo = Foo::builder().x(5).y(6).build().unwrap();
    // assert_eq!(foo, Foo { x: 5, y: 6 });
}

When the user provides #[builder(postbuild)], the macro won't implement a default PostBuild impl. Instead, the user has to implement this trait manually. This allows user to implement custom validation logic.


Note: Some test cases are commented out, as the initial draft of this feature breaks these test cases. Follow-up commits will fix those issues. As such, the PR is a draft. When the test cases are fixed and the code is polished, it is marked as "Ready to review".

@ZENOTME
Copy link

ZENOTME commented Jun 12, 2025

Hi, seems this pr has been a long time, I'm curious what is the status of this feature?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allow invariant checks in .build()
2 participants