-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow invariant checks in .build()
#67
Comments
Just stumbled upon this issue while looking through the repo, but you could do something like this: pub struct S {
xy: Xy
}
pub struct Xy {
x: i32,
y: i32,
}
impl Xy {
pub fn new(x: i32, y: i32) -> Result<Self, Whatever> {
if x < y {
Ok(Self { x, y })
} else {
Err(/* whatever */)
}
}
// also add some getters for x and y
} i.e. just encode the invariants into the type system |
@benluelo its like a builder pattern and I have another idea: pub struct S {
x: i32,
y: i32,
}
pub struct SBuilder {
pub x: i32,
pub y: i32,
}
impl SBuilder {
pub fn build(self) -> Result<S, Whatever> {
if self.x < self.y {
Ok(S { x, y })
} else {
Err(/* whatever */)
}
}
} |
I would implement it like this: fn build(self) -> Result<S, Whatever> {
…
validate(S {x, y})
} Where I would call it something like @idanarye Does this look fine to you? |
I can tackle this if @idanarye approves. |
What's the signature of |
Since the crate is split now and we can bring in regular structs, who about something like this: #[derive(TypedBuilder)]
#[builder(postbuild)]
struct S {
x: i32,
y: i32,
}
impl PostBuild for S {
type Output = Result<Self, Whatever>;
fn process(self) -> Self::Output {
validate(&self)?; // or just do the validation here
Ok(self)
}
}
|
Nice approach! Using |
I wonder about that. I think always using |
Yeah I agree, we should always use the |
I created an initial draft PR over at #95 which implements this feature. It should be noted that it currently is a WIP PR. |
I want something like this:
When
.build()
is called, I also wantcheck_rep
to be called.The text was updated successfully, but these errors were encountered: