Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Де-clauses

Обмеження також може бути виражене за допомогою 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();
}

Дивіться також:

RFC, struct, and trait