Impl <> blocks syntax


#1

Dear Masters.
I really want to find out what is the difference between simple
impl Trait<> for Name
and
impl<> Trait<> for Name


#2

You need to use the second one when either the Trait or your Name type is generic. This allows you to say "implement Trait for Name<T> for any generic type, T".

Have you tried seeing what the compiler says when you use one form and it expects the other? Here’s an example which may show the difference between the two forms, you should be able to copy/paste it into the playground.

trait Concrete {}

trait Generic<T> {}

struct Foo;

impl Concrete for Foo {}
impl<T> Concrete for Foo {}

impl Generic<T> for Foo {}
impl<T> Generic<T> for Foo {}

fn main() {}

#3

The <T: C> in impl<T: C> is a universal quantifier, so you’re meant to read it as “for all T where T is a C”. On the other hand, the <T> in Trait<T> is where you actually use a type, maybe a type that you declared and quantified in the impl<>, but it can also be any other type.


#4

Thanks.
I doubtfully thought that i went through the syntax of Rust.
Could you please give a decent ref that covers this topic.


#5

Here what i’ve got trying:
trait A {
fn prin(self,x:T);
}
struct Foo;

impl A for Foo {
fn prin(self,x:T){println!{"{}",x}}
}

fn main() {
let x=Foo{};
x.prin(2);
}
error[E0412]: cannot find type T in this scope
–> src\main.rs:7:8
|
7 | impl A for Foo {
| ^ did you mean A?

error[E0412]: cannot find type T in this scope
–> src\main.rs:8:20
|
8 | fn prin(self,x:T){println!{"{}",x}}
| ^ did you mean A?
???


#6

The A trait is generic (A)


#7

HOORAY! I Think ive got it.
We declare a generic trait and then in impl blocks define its methods realization with different types for certain structs or whatever ???


#8

Yes. With impl<T> you get a new copy of the entire impl for every value of T.