Force Associated Types to Have a Trait

Is it possible to create associated types that are forced to have a specific trait? I am thinking of something like this:

trait SomeTrait {}
trait SomeOtherTrait {
type assoc_type; // where assoc_type needs to have implemented SomeTrait! 

fn f(&self) -> Self::assoc_type;
}

The reason I need this is that I want to be able to use the fact that the return type of f has the trait SomeTrait. Is this possible to achieve somehow or is there a more elegant solution to this problem anyways? Thx! :slight_smile:

1 Like
trait MyTrait {
    type Assoc: AnotherTrait;
}

But I'm sure it's somewhere in The Book.

3 Likes

Oh man, I feel like an idiot now, so simple! Can't believe I didn't just try this before posting. Thanks for the help though! (:

I was curious and looked for associated type bounds in the book. It's not there although there is an open issue for adding it. It is in the reference.

2 Likes

Another approach to gain this knowledge (though not necessarily an approach when acutely searching for it) is to learn from important examples in the standard library:

pub trait IntoIterator {
    type Item;
    type IntoIter: Iterator<Item = Self::Item>;

    fn into_iter(self) -> Self::IntoIter;
}
3 Likes

I see, that actually seems like a good idea, I'll try to consult the standard library first for future questions! Thx! :slight_smile: