We have a weird inconsistency with default type parameters and generic trait impls. Let's consider this example:
pub struct Foo<T = u32> { val: T }
impl<T: Default> Default for Foo<T> {
fn default() -> Self {
Self { val: Default::default() }
}
}
fn main() {
let foo = Foo::default();
}
It fails to compile with the following message:
error[E0283]: type annotations needed for `Foo<_>`
--> src/main.rs:10:9
|
10 | let foo = Foo::default();
| ^^^ --- type must be known at this point
|
= note: cannot satisfy `_: Default`
note: required for `Foo<_>` to implement `Default`
--> src/main.rs:3:18
|
3 | impl<T: Default> Default for Foo<T> {
| ------- ^^^^^^^ ^^^^^^
| |
| unsatisfied trait bound introduced here
help: consider giving `foo` an explicit type, where the type for type parameter `T` is specified
|
10 | let foo: Foo<T> = Foo::default();
| ++++++++
Amusingly, <Foo>::default()
and let foo: Foo = Foo::default()
work as expected, so it does not look like some fundamental issue. The same applies to const generics with default value as well (e.g. Foo<const N: u32 = 42>
).
Why exactly compiler can't use the default type parameter to infer T
? Are there any plans to fix it?