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

How to make Builder implement Deserialize? #68

Open
lcmgh opened this issue Jun 8, 2022 · 3 comments
Open

How to make Builder implement Deserialize? #68

lcmgh opened this issue Jun 8, 2022 · 3 comments

Comments

@lcmgh
Copy link

lcmgh commented Jun 8, 2022

Hi!

I want to use the builder together with config-rs to use config from a file as input for the builder. For that the builder struct must support Deserialize. How can I achieve that?

Thanks

@idanarye
Copy link
Owner

idanarye commented Jun 8, 2022

I'm not sure what you want to do even makes sense. TypedBuilder has the builder's state (which fields were already set) encoded in its type (in the generic parameters actually), which means it must be known at compile time.

When you think about deserializing a builder, you probably think about something like this:

#[derive(TypedBuilder)]
struct Foo {
    #[builder(default = 1)]
    bar: i32,
    #[builder(default = 2)]
    baz: i32,
}

assert_eq!(
    Foo::builder(),
    deserialize::<FooBuilder>(r#"{}"#),
);
assert_eq!(
    Foo::builder().bar(3),
    deserialize::<FooBuilder>(r#"{"bar": 3}"#),
);
assert_eq!(
    Foo::builder().baz(4),
    deserialize::<FooBuilder>(r#"{"baz": 4}"#),
);
assert_eq!(
    Foo::builder().bar(3).baz(4),
    deserialize::<FooBuilder>(r#"{"bar": 3, "baz": 4}"#),
);

The problem is that these are four distinct types! deserialize::<FooBuilder>() is dealing with a runtime string, so it can't tell at compile time which fields are set and which aren't.

@lcmgh
Copy link
Author

lcmgh commented Jun 9, 2022

Use case:

  • There is a library that ships a Builder with default values
  • Library client microservice wants to use default values and merge in user configured fields

On client side I want to load config from a file that ovewrites certain fields. With rust-derive-builder I was able to use the Builder type for my settings and merge in user specific attributes from the config file. After retrieving the config I still have to call the build method but I got all the data without any additional setup.

@Niedzwiedzw
Copy link

I'm interested in this feature for the same reason as above

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

No branches or pull requests

3 participants