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

Create a Builder from related struct #263

Closed n3wtron closed 2 years ago

n3wtron commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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