-
Notifications
You must be signed in to change notification settings - Fork 82
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
CustomDefault #3
Comments
Since I think there are three approaches
Option 1:
Option 2:
Option 3:
By the principle of exclusion, I'd say lets start with option 3, i.e. let This artificial restriction gives us some legroom (=flexibility):
|
As @killercup suggested the CustomDefault-crate could also implement a constructor with some required parameters if not all fields are defaulted. The method name could be user-defined and default to |
Just found https://mcarton.github.io/rust-derivative/Default.html#setting-the-value-of-a-field #[derive(Debug, Derivative)]
#[derivative(Default)]
struct Foo {
foo: u8,
#[derivative(Default(value="42"))]
bar: u8,
}
println!("{:?}", Foo::default()); // Foo { foo: 0, bar: 42 } Looks very good. I would have preferred |
I am preparing a PR for the next days. Proposed API / DocumentationYou can define default values for each field via annotation by
#[derive(Builder, PartialEq)]
struct Lorem {
#[builder(default=r#"format!("Hello {}!", "World")"#)]
pub ipsum: String,
}
fn main() {
// If we don't set the field `ipsum`,
let x = LoremBuilder::default().build().unwrap();
// .. the custom default will be used for `ipsum`:
assert_eq!(x, Lorem {
ipsum: String::from("Hello World!"),
});
} Note: The expression will be evaluated with each call to Discussion
|
If you haven't seen it, serde does a really elegant job handling this (docs). Using |
@TedDriggs thx for the hint. I was already thinking about using |
e.g. `#[builder(default="\"Hello World!\"")]`
e.g. `#[builder(default="\"Hello World!\"")]` or just `#[builder(default)]` without value to delegate to `Default`
e.g. `#[builder(default="\"Hello World!\"")]` or just `#[builder(default)]` without value to delegate to `Default`
published with v0.4.0 |
The builder pattern allows us to set optional values on a struct—but how do we determine the default values for those fields? Rust's default answer (hehe) is of course
std::default
with its#[derive(Default)]
and custom-writtenimpl Default
.At first, we can
#[derive(Default)]
so they can doMyStruct::default().setter(42)
,impl MyStruct { pub fn new(…) {…} }
so they can doMyStruct::new(…).setter(42)
.It would be really nice to also offer a way to derive/generate a
Default
impl with custom values, e.g.:(How) should we do this? (I don't think it's necessary to have this early on, and it should probably be a separate crate.)
@colin-kiegel already suggestion this in DanielKeep/rust-custom-derive#18.
The text was updated successfully, but these errors were encountered: