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 从句的情况下表达
use std::fmt::Debug;

trait PrintInOption {
    fn print_in_option(self);
}

// Because we would otherwise have to express this as `T: Debug` or 
// use another method of indirect approach, this requires a `where` clause:
impl<T> PrintInOption for T where
    Option<T>: Debug {
    // We want `Option<T>: Debug` as our bound because that is what's
    // being printed. Doing otherwise would be using the wrong bound.
    fn print_in_option(self) {
        println!("{:?}", Some(self));
    }
}

fn main() {
    let vec = vec![1, 2, 3];

    vec.print_in_option();
}

另请参阅

RFCstructtrait