-
Hi, very cool crate! I am wondering, whether it is possible to create a builder for a struct, in a way that I can add conditions that only certain combinations of fields are allowed. Let's say I have a struct with one regular and three optional fields. Can I make builder to allow finishing only when at least one (any of the three optional fields) is set? So after the first required field, at least one of the three optional fields has to be set, for example, before builder can finish. It was not so clear from the docs for me. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, thank you for creating a discussion! Today, it's not possible to express a precondition such as "at least one" at compile time. You can validate for this property at runtime using Fallible Builders approach by implementing the validation using the method builder syntax: struct Example {
regular: u32,
x1: Option<u32>,
x2: Option<u32>,
x3: Option<u32>,
}
#[bon::bon]
impl Example {
#[builder]
fn new(
regular: u32,
x1: Option<u32>,
x2: Option<u32>,
x3: Option<u32>,
) -> anyhow::Result<Self> {
if x1.is_none() && x2.is_none() && x3.is_none() {
return Err(anyhow::anyhow!("At least one of x1, x2, x3 must be set"));
}
Ok(Self {
regular,
x1,
x2,
x3,
})
}
}
let example = Example::builder()
.regular(42)
.x1(1)
.build()?; In theory the simplest form of "at least 1 from the group of fields is set" check could be supported at compile time, but in the current state of Rust's diagnostics reporting the compile error messages you'd get from that would be awful. And if you'd like to go further and have "at least 2, 3, ... N from the group of fields is set", or "exactly N fields from the group is set", then the compile-time complexity of such checks blows. This would yield considerable compilation time overhead. An existing attempt at implementing that is in const-typed-builder crate. There is an issue about having this feature in bon though (#110), but it needs a lot of design yet. |
Beta Was this translation helpful? Give feedback.
Hi, thank you for creating a discussion! Today, it's not possible to express a precondition such as "at least one" at compile time. You can validate for this property at runtime using Fallible Builders approach by implementing the validation using the method builder syntax: