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