Why does Rust require a generic type declaration after the keyword "impl"?

Defining generic type methods requires adding generic types after impl:

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

I feel the removal <T>seems OK:

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

Is this some special consideration?

+6
source share
1 answer

Rust allows you to write blocks implthat apply only to a specific combination of type parameters. For instance:

struct GenericVal<T>(T);

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

Here the type GenericValis common, but implnot itself .

, impl, GenericVal<T>, impl ( T T).

struct GenericVal<T>(T);

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

, , .

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

impl<V> GenericVal<V, V> {
    fn foo(&self) {
        // method foo() is only defined when T = U
    }
}
+12

Source: https://habr.com/ru/post/1682903/


All Articles