Interpreting the syntax for trait


#1

I have trouble understanding the following syntaxes:

One:

pub struct X<T>
     where T: Atrait

Two:

impl<T> Something for X<T>
    where T: Atrait

Could someone please explain me what the interpretation is?

Thank you.


#2

One: structure X that contains a type T, which can be any type that implements Atrait.

Two: for any T (which implements Atrait), implement trait Something for struct X containing T.

In both cases these constructs act like templates, meaning type-specific code will be generated at compile time for any type you use them with (so struct X<T> is duplicated as struct X<Foo>, struct X<Bar>, etc. and each gets its optimized layout and implementation)


#3

Thanks for the previous reply. Few more questions:
You wrote:
pub structX where T: Atrait

means, “struct X that contains a type T”. Does it mean that X is a struct that has one member of type T?

pub fn func1<T>(&self, argu: &T) -> Result() {
    where T: Sometrait + Anothertrait    
     .....
}

Does the above definition mean that, "func1 is a function that implements the two traits Sometrait and Anothertrait for some type T?

And how about the following? It beats me completely :slight_smile:

impl<T> Atrait for X<T>
where T: Atrait

#4

Not necessarily. It means that “X is generic over T”, or whatever the official term is, which can mean any number of things.

But usually it means that there is at least one member that uses T. You will have to look at the declaration of X to learn more.

The function doesn’t implement the traits. The function receives a T, and it requires that someone, somewhere had to implement these traits for T.

“For any T that implements Atrait, X also implements this trait.”

I can give more concrete examples if you like.


#5

Thank you so much.

I will be much obliged if you could post more examples.


#6

Maybe these aren’t the best examples:

https://play.rust-lang.org/?gist=580bbb872d15e5909625160b3e2d7d29&version=stable