Where句
トレイト境界は、{の直前にwhere句を導入することでも設けることができます。whereはさらに、型パラメータだけでなく任意の型に対して適用できます。
where句のほうが有効なケースには例えば以下のようなものがあります。
- ジェネリック型とジェネリック境界に別々に制限を加えたほうが明瞭になる場合
impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}
// `where`を用いてジェネリック境界を設けます。
impl <A, D> MyTrait<A, D> for YourType where
A: TraitB + TraitC,
D: TraitE + TraitF {}
where句の方が通常の構文より表現力が高い場合。この例では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 {
// 出力されるのが`Some(self)`であるため、この関数の
// ジェネリック境界として`Option<T>: Debug`を使用したい。
fn print_in_option(self) {
println!("{:?}", Some(self));
}
}
fn main() {
let vec = vec![1, 2, 3];
vec.print_in_option();
}