Where 从句
可以使用 where
从句在开头的 {
之前立即表达约束,而不是在类型第一次出现时。此外,where
从句可以将约束应用于任意类型,而不仅仅是类型参数。
where
从句有用的几种情况
- 当分别指定泛型类型和约束更清晰时
impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}
// Expressing bounds with a `where` clause
impl <A, D> MyTrait<A, D> for YourType where
A: TraitB + TraitC,
D: TraitE + TraitF {}
- 当使用
where
从句比使用普通语法更具表达力时。此示例中的impl
不能直接在没有where
从句的情况下表达