Skip to content
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

Create a Builder from related struct #263

Closed
n3wtron opened this issue Sep 24, 2022 · 2 comments
Closed

Create a Builder from related struct #263

n3wtron opened this issue Sep 24, 2022 · 2 comments

Comments

@n3wtron
Copy link

n3wtron commented Sep 24, 2022

It would be great to have the ability to create a builder from the related struct.
Something like

use derive_builder::Builder;

#[derive(Debug, Clone, Builder)]
pub struct User {
    pub id: Option<String>,
    pub username: String,
    pub email: String,
}

fn doSomething(user: &User) -> Result<User> {
    let user_with_id = user.toBuilder().id(.....).build()?;
}
@TedDriggs
Copy link
Collaborator

This was previously discussed in #170. I am still not inclined to pursue this, as Rust provides efficient struct-update syntax in the following form:

let user_with_alt_id = User {
    id: "...".into(),
    ..old_user
};

Additionally, there are too many open questions about the exact behavior of such a method to generate an implementation - including, but not limited to:

  1. Does this method invoke the setters of the builder with the values from the input struct, or directly initialize the fields? Since setters may have custom behavior, this decision could have externally-visible side-effects.
  2. What happens to fields from the struct that are skipped in the builder? Their values will be lost; is this expected by the person using the method?
  3. Does this method consume the input struct? In idiomatic Rust, the answer would be "yes", but the naming in this example suggests that you'd prefer it instead implicitly clone the fields.

Given the number and severity of questions that don't have clear answers, it's best for authors wishing to provide this functionality to hand-build this method themselves for the structs where there's a good reason for it.

@n3wtron
Copy link
Author

n3wtron commented Sep 26, 2022

Thank you very much for the fast reply and sorry for the duplication.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants