Difference in impl block with generics

Having:

struct Type<T>{}

What is the difference between:

impl<T> Type<T>{}

and

impl Type<T>{}

And where could I read about it in detail?
Thank you

If you omit the first <T> Rust thinks the remaining <T> refers to a concrete type, which is likely not what you want. But if you instead insert a known type it makes more sense:

use std::sync::Mutex;

struct MyMutex<T>(Mutex<T>);

impl<T> MyMutex<T> {
    pub fn lock(&self) {
    }
}

impl MyMutex<String> {
    pub fn lock_and_set_string(&self, s: &str) {
    }
}

There's a note about this in Rust By Example

3 Likes

You could read impl<T> as "for all types T, implement the following". So in a way, <T> written behind impl is some sort of universal quantifier.

Note that strictly speaking, the implementation is implicitly restricted to types T which are Sized. So if you want to implement something really for all types T, you would have to write impl<T: ?Sized>.

2 Likes

Thanks, I really like that answer.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.