Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rust don't use default generic parameter type

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?

like image 342
Michael Ilyin Avatar asked Sep 06 '19 15:09

Michael Ilyin


People also ask

Does Rust support generic types?

Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics.

What are generics Rust?

In Rust, generics refer to the parameterization of data types and traits. Generics allows to write more concise and clean code by reducing code duplication and providing type-safety. The concept of Generics can be applied to methods, functions, structures, enumerations, collections and traits.

Is generic type parameter?

Generic MethodsA type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.


1 Answers

When you don't precise 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.

like image 105
Denys Séguret Avatar answered Oct 22 '22 12:10

Denys Séguret