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?
Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics.
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.
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.
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
Note that in c:C
, there's no type inference at all: Omitting <_>
or <SomeType>
means the default type applies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With