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

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 절을 사용하는 것이 일반 구문을 사용하는 것보다 더 표현력이 좋을 때. 이 예제의 implwhere 절 없이는 직접 표현할 수 없습니다:
use std::fmt::Debug;

trait PrintInOption {
    fn print_in_option(self);
}

// 그렇지 않으면 `T: Debug`로 표현하거나
// 다른 간접적인 방법을 사용해야 하므로, 여기에는 `where` 절이 필요합니다:
impl<T> PrintInOption for T where
    Option<T>: Debug {
    // 출력되는 것이 `Option<T>`이므로, 바운드로 `Option<T>: Debug`를 원합니다.
    // 다르게 하면 잘못된 바운드를 사용하는 셈이 됩니다.
    fn print_in_option(self) {
        println!("{:?}", Some(self));
    }
}

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

    vec.print_in_option();
}

참고:

RFC, struct, 그리고 trait