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

Combining `build_method(into)` with `setter(skip)` on a field with a generic parameter results in compilation error #118

Closed epimeletes closed 11 months ago

epimeletes commented 11 months ago

This code:

#[derive(typed_builder::TypedBuilder)]
#[builder(build_method(into=Bar))]
struct Foo<T> {
    #[builder(default, setter(skip))]
    foo: Option<T>,
}

struct Bar;

impl<T> From<Foo<T>> for Bar {
    fn from(_value: Foo<T>) -> Self {
        Self
    }
}

yields this error:

error[E0282]: type annotations needed for `Option<T>`
 --> sandbox\src\main.rs:5:5
  |
5 |     foo: Option<T>,
  |     ^^^
  |
help: consider giving `foo` an explicit type, where the type for type parameter `T` is specified
  |
5 |     foo: Option<T>: Option<T>,
  |        +++++++++++
epimeletes commented 11 months ago

Actually, there is another error coming up if the into type is itself generic:

#[derive(typed_builder::TypedBuilder)]
#[builder(build_method(into=Bar<T>))]
struct Foo<T> {
    #[builder(default)]
    foo: Option<T>,
}

struct Bar<T>(Option<T>);

impl<T> From<Foo<T>> for Bar<T> {
    fn from(value: Foo<T>) -> Self {
        Self(value.foo)
    }
}

results in

error: unexpected end of input, expected an expression
  |
2 | #[builder(build_method(into=Bar<T>))]
  | 

In my current use case, Bar is not generic so a fix to the first problem would be already very helpful. However, if conversion to generic types could be supported that might be useful as well.

idanarye commented 11 months ago

The problem is that this generates this build method:

#[allow(dead_code, non_camel_case_types, missing_docs)]
#[automatically_derived]
impl<T> FooBuilder<T, ()> {
    #[allow(clippy::default_trait_access, clippy::used_underscore_binding)]
    pub fn build(self) -> Bar {
        let () = self.fields;
        let foo = ::core::default::Default::default();
        #[allow(deprecated)]
        Foo { foo }.into()
    }
}

Without the conversion, Foo { foo } would have gotten the type of the concrete Foo (because that would have been the return value of the function, and there would have been no .into(). But with the conversion the compiler has no way to know the value of the Foo { foo } - which also means it has no way to know the value of the foo. into=Bar))] As for the second issue - I'm afraid you are going to have to use the turbofish:

#[builder(build_method(into=Bar::<T>))]
epimeletes commented 11 months ago

Thank you for a very quick fix! And how silly of me not to try the turbofish, thanks for pointing this out as well. (The error message wasn't exactly helpful here, but I guess that's what we get with macros.)