18

I want to create generic structure with default type. But Rust compiler still requires me to specify explicit type when creating my structure.

struct A {}

struct C<T = A> {
    t: Option<T>
}

fn main() {
    let c = C { t: None };
}

Rust compiler shows this error:

error[E0282]: type annotations needed for `C<T>`
 --> src/main.rs:8:9
  |
8 | let c = C { t: None };
  |     -   ^ cannot infer type for `T`
  |     |
  |     consider giving `c` the explicit type `C<T>`, where the type parameter `T` is specified

How can I allow user of my code to omit generic parameter?

Boiethios
  • 38,438
  • 19
  • 134
  • 183
Michael Ilyin
  • 717
  • 8
  • 15
  • If you want to build a `struct` without let the user bother about the generic types, you should use the builder pattern. – Boiethios Sep 06 '19 at 15:19
  • 4
    The compiler here fails to determine the type of T is the default one because it tries to infer the type from the right part. You can help it with this simple hint: ` let c:C = C { t: None };` – Denys Séguret Sep 06 '19 at 15:31

1 Answers1

12

When you don't explicitly specify a type in a variable binding (left of the assignment), the compiler must infer it.

Here, the value isn't precise enough (None could be anything).

A solution is to declare a type in the binding. You don't have to give a type to T, if you write just C, the default type for T is applied:

let c: C = C { t: None };

It's debatable

  • whether it's a compiler bug or not (I don't think it is but it can be argued that a human sees no ambiguity here)
  • whether it should be fixed or not (I don't think it should as more complex cases could be ambiguous or hard to decipher when there are multiple inference locations)

Note that in c:C, there's no type inference at all: Omitting <_> or <SomeType> means the default type applies.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I'm quite sure this is not a bug. In a realistic setting (ie where `c` is actually used) this is less likely to happen. – Peter Hall Sep 06 '19 at 15:58
  • @PeterHall I also tend to think that "fixing" it would fuss the logic and also make it harder for humans to decipher the code in less trivial cases. – Denys Séguret Sep 06 '19 at 15:59
  • Thank you! Though tt's still unclear why compiler can infer T=A in left expression, but can't do it in right – Michael Ilyin Sep 06 '19 at 20:58