Benjamin Lindley
Benjamin Lindley

Reputation: 103703

Putting a requirement on the type of a member of a trait implementation

I have a trait that implements another trait:

trait RandomAccessIterator : Sub + VariousOthers {}

How do I specify, that for all implementations of this trait, the result of the subtraction (the Output type within Sub) must be of a certain type, such as isize? That way, if I write a generic function which uses objects implementing this trait, I know (and more importantly, the compiler knows) that the result of A - B is type isize.

Upvotes: 0

Views: 122

Answers (1)

Shepmaster
Shepmaster

Reputation: 430673

trait RandomAccessIterator : Sub<Output = isize> + VariousOthers {}

As discussed in The Rust Programming Language chapter about associated types in the section for trait objects with associated types:

The N=Node syntax allows us to provide a concrete type, Node, for the N type parameter. Same with E=Edge. If we didn’t provide this constraint, we couldn’t be sure which impl to match this trait object to.

While this isn't a trait object, the same syntax applies. Most people run into this when using operators like Mul,

Upvotes: 2

Related Questions