Supertrait-associated type bounds

Hi! I want to define a trait that uses Iterator as supertrait. But I can't use the Item type of Iterator trait inside of my trait, the compiler says it is unstable. Is there any workaround for this or would you suggest any other design?

This is a minimal example:

trait Lex: Iterator<Item: std::cmp::PartialEq> {

	fn peek(&mut self) -> Self::Item;

	fn r#match(&mut self, c: Self::Item) -> bool {
		if self.peek() == c {
			self.next();
			return true;
		}
		false
	}

	fn r#match_while<T: Fn(Self::Item) -> bool>(&mut self, filter: T) -> bool {
		if filter(self.peek()) {
			self.next();
			while filter(self.peek()) {
				self.next();
			}
			return true;
		}
		false
	}
}

I am encountering some missing type-system features like this while I am experimenting with Rust, and
I attribute this to the youth of the language and it's community. What do you think about that? I hope Rust will have an even rich type system in the future.

You can rewrite your bound like this:

trait Lex: Iterator where Self::Item: PartialEq
1 Like

Thanks. I wonder why this works while my code doesn't? Is there any semantic difference between them?

There's no semantic difference.

T: Iterator<Item: PartialEq> is a new shorthand syntax for T: Iterator, T::Item: PartialEq. The new syntax has not been stabilized yet because there are still questions about its design and implementation:

https://github.com/rust-lang/rust/issues/52662

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.