31

Defining the methods of generic type requires adding generic types after impl:

struct GenericVal<T>(T,);
impl <T> GenericVal<T> {}

I feel that removing <T> seems OK:

struct GenericVal<T>(T,);
impl GenericVal<T> {}

Is it any special consideration?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
  • 3
    For anyone else wondering the same thing, check out my article [here](https://dev.to/talzvon/rust-generic-types-in-method-definitions-4iah) where I try to explain why this is required with simple examples. – John Apr 04 '21 at 17:13

1 Answers1

43

Rust allows you to write impl blocks that apply only to some specific combination of type parameters. For example:

struct GenericVal<T>(T);

impl GenericVal<u32> {
    fn foo(&self) {
        // method foo() is only defined when T = u32
    }
}

Here, the type GenericVal is generic, but the impl itself is not.

Thus, if you want to write an impl block that applies for all GenericVal<T> types, you must first declare a type parameter on the impl itself (otherwise, T would try to look up a type named T).

struct GenericVal<T>(T);

impl<T> GenericVal<T> {
    fn foo(&self) {
        // method foo() is always present
    }
}

This declaration also lets you have a single type parameter that can be used multiple times, forcing the types to be the same.

struct GenericVal<T, U>(T, U);

impl<V> GenericVal<V, V> {
    fn foo(&self) {
        // method foo() is only defined when T = U
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
  • 1
    However it seems that the compiler can infer from the type parameters of `GenericVal` instead of `impl`. Could you explain why the `impl` syntax is a *must*? – yeshengm Jan 12 '19 at 21:37
  • I don't think it's strictly necessary, but if helps prevent ambiguities. What if someone introduced a type named `V` in the scope of that module? Is the use of `V` in the `impl` referring to the concrete type `V` (like the first example in my answer) or to an implicit generic parameter `V`? – Francis Gagné Jan 14 '19 at 00:28
  • @yeshengm as Francis said impl can be used to implement for specific types, you can think signature impl GenericVal {} like impl is a declaration and GenericVal is the usage for that declared type. – Akshay Naik May 30 '20 at 17:55