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

feature: add an `opt` version of the builders when `strip_option` is enabled.

Open sosthene-nitrokey opened this issue 9 months ago • 7 comments

Hi!

Currently strip_option prevents the actual setting of None, forcing to use two code paths when one wants to maybe build with None. I propose the following. When using strip_option, a second setter is added, with an _opt suffix, that takes an option.

Here is an example:

Current version

#[derive(TypedBuilder)]
struct SomeStruct {
    #[builder(default, setter(strip_option)]
     inner: Option<u32>,
}

fn some_fn(value: Option<u32>) -> SomeStruct {
    match value {
        None => SomeStruct::builder().build(),
        Some(v) => SomeStruct::builder().inner(v).build(),
    }
}

Proposal:

#[derive(TypedBuilder)]
struct SomeStruct {
    #[builder(default, setter(strip_option)]
     inner: Option<u32>,
}

/// The old way still works the same
fn old_way(value: Option<u32>) -> SomeStruct {
    match value {
        None => SomeStruct::builder().build(),
        Some(v) => SomeStruct::builder().inner(v).build(),
    }
}

fn new_way(value: Option<u32>) -> SomeStruct {
    /// There are now 2 ways to set `inner`, allowing both uses, but privileging the `Some` case as intended.
    SomeStruct::builder().inner_opt(value).build()
}

Limitations

This would be a breaking change, since it would break the compilation of structures having for example an inner and an inner_opt field. This could be made opt-in for example by requiring the user to give a name to the _opt version.

sosthene-nitrokey avatar Sep 19 '23 09:09 sosthene-nitrokey