Trait functions can't return `impl Iterator`?

I’m getting a confusing error message. The following code:

trait MyTrait {
    fn func(self) -> impl Iterator<Item=u8>;

Gives this error message:

error[E0562]: impl Trait not allowed outside of function and inherent method return types.

I thought func was a function? Does it simply mean that trait functions can’t have impl return types?

func is an “associated method” or (informally) a “trait method.” When the error message says “function” it means a free function. (this is not very clear, though)

Yes. You should use an associated type:

trait MyTrait {
    type Output: Iterator<Item=u8>;

    fn func(self) -> Self::Output;
1 Like

Thanks. Would it be at all possible to make the error message slightly more informative for this special case?