我有一个实现另一个特征的特征:
trait RandomAccessIterator : Sub + VariousOthers {}
我如何指定,对于这个特征的所有实现,减法的结果(Sub
中的 Output
类型)必须是某种类型,例如作为 大小
?这样,如果我编写一个使用实现此特征的对象的通用函数,我知道(更重要的是,编译器知道)A - B
的结果是 isize
.
最佳答案
trait RandomAccessIterator : Sub<Output = isize> + VariousOthers {}
如 The Rust Programming Language 中所述关于associated types的章节在 trait objects with associated types 部分:
The
N=Node
syntax allows us to provide a concrete type,Node
, for theN
type parameter. Same withE=Edge
. If we didn’t provide this constraint, we couldn’t be sure whichimpl
to match this trait object to.
虽然这不是特征对象,但适用相同的语法。大多数人都会遇到这个 when using operators like Mul
,
关于rust - 对特征实现成员的类型提出要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516770/