impl<T> seems to be redundant

I believe that if we have:

struct AStruct<T>
{
}

we should be able to do:
impl AStruct<T>//here notice no impl<T> as it is simply in my opinion redundant
{
}

Any thoughts?

In that case it would not be immediately obvious if T is an existing type or type parameter.

1 Like

I believe that it is immediately obvious by having:

AStruct<T>
struct T;

struct AStruct<T> {}

impl AStruct<T> {
    fn foo() {}
}

would only implement the foo method for the type AStruct<T> where T is a struct. It wouldn't implement it for AStruct<T> for all types T like impl<T> AStruct<T> does.

Is this valid rust?

1 Like

The impl<T> part declares a generic type variables and the AStruct<T> part uses it. This separation allows more complex impl blocks:

impl<T> AStruct<Option<T>> {}

impl<T, E> AStruct<Result<T, E>> {}

impl<T> AStruct<Box<dyn Iterator<Item = T>>> {}

impl AStruct<String> {}

...
4 Likes

Thanks, so do I understand it correctly that having the below:

struct T;
impl aStruct<T>
{
}

aStruct type will work only for struct T? Some sort of specialization?

Conceptually, yes. But usually when we refer the term specialization it means this WIP unstable feature.

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.