idanarye / rust-typed-builder

Compile-time type-checked builder derive
https://crates.io/crates/typed-builder
Apache License 2.0
904 stars 52 forks source link

about the default value #135

Closed 2moe closed 7 months ago

2moe commented 7 months ago
    use typed_builder::TypedBuilder;

    #[derive(Debug, TypedBuilder)]
    struct Foo {
        // #[builder(default = Foo::default().n)]
        #[builder(default)]
        n: u8,
    }

    impl Default for Foo {
        fn default() -> Self {
            Self { n: 100 }
        }
    }

    let Foo { n } = Foo::builder().build();

    // assert_eq!(n, 0);
    if n == u8::default() {
        eprintln!("u8::default")
    }

    // assert_eq!(n, 100);
    if n == Foo::default().n {
        eprintln!("Foo::default")
    }

As in the example above, I want the default to be Foo::default().n, not u8::default().

The behavior is like #[serde(default)].

Aside from manually specifying Foo::default().n, is there an easier way to specify the default value as the default value of the field corresponding to the structure itself, rather than the default value of the field type?

idanarye commented 7 months ago

Just do it the other way around - define the Default using the builder:

#[derive(Debug, TypedBuilder)]
struct Foo {
    #[builder(default = 100)]
    n: u8,
}

impl Default for Foo {
    fn default() -> Self {
        Self::builder().build()
    }
}
2moe commented 7 months ago

Thanks