Skip to content

Is it possible to use some sort of set theory when building struct with optional fields #223

Answered by Veetaha
Nicceboy asked this question in Q&A
Discussion options

You must be logged in to vote

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"));

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Nicceboy
Comment options

Answer selected by Nicceboy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants