Why I cannot return impl Trait from a trait method?


I cannot clearly understand why I cannot return impl Trait from a trait method, but I can do it from a structure method, see this example:

trait T0 {}

impl T0 for i32 {

struct S0;

impl S0 {
    // This is ok!
    fn foo() -> impl T0 {

trait T1 {
    // This generates error E0562
    fn foo() -> impl T0;

Thank you.

Because impl Trait is a special syntax that will result in one of many different types being returned. You can use an associated type instead:

trait T1 {
    type MyT0: T0;

    fn foo() -> Self::MyT0;

Sorry I didn't really get which is the difference between the structure method and trait method version.

I was thinking that returning impl Trait is a sort of indication for the compiler that tells it: "hey, here I want to return a type that is implementing some trait T, please check that is true when somebody will do", so I cannot understand why I cannot do inside a trait. :thinking:

impl Trait in a return type means you don't want to, or can't, name the return type, there's still only one return type and what that type is is inferred by what's in the function's body.


Ah! Ok, so I did get it a completely different way, my bad! Thank you for the clarification! :+1: