colin-kiegel / rust-derive-builder

derive builder implementation for rust structs
https://colin-kiegel.github.io/rust-derive-builder/
Apache License 2.0
1.32k stars 88 forks source link

[Feature Request] Add boolean setter to set `bool` by simple method call #218

Closed jquesada2016 closed 2 years ago

jquesada2016 commented 3 years ago

Reading through the docs, I did not see if this was already possible, but it would be very convenient to be able to (un)set a bool field a simple method call. Let's take the following.

struct MyStruct {
  true_bool: bool,
}

It would nice to do the following:

// This
MyStructBuilder::default().true_bool().build();

// Instead of this
MyStructBuilder::default().true_bool(true).build();

And in the cases where a false bool should be set, perhaps:

#[derive(Builder)
struct MyStruct {
  #[builder(setter(bool = "false") // could also be "false/true" to allow for either setting or unsetting
  bool_field: Option<bool>
}

// The #[builder(setter(bool = "true")] case
MyStructBuilder::default().set_bool_field().build();

// The #[builder(setter(bool = "false")] case
MyStructBuilder::default().unset_bool_field().build();

// The #[builder(setter(bool = "true/false")] case
MyStructBuilder::default().set_bool_filed().unset_bool_field().build();
TedDriggs commented 2 years ago

You can add inherent methods of your own to the builder using an additional impl block; I'd suggest doing that for this case. The character savings otherwise are too small to justify the added complexity for the macro.