12.6 Where clauses

바인드 대상은 또한 where절로 {을 열기 전에 타입이 처음 선언되기도 전에 즉시 표시될 수 있다. 추가로 where절은 단순 타입 매개변수보다 임의의 타입에 바인드 하는데 적합하다.

where절은 유용하게 사용할 수 있는 경우:

  • 제네릭 타입의 선언과 바인드 대상의 분리를 분명히 하고자 할 때:
  • When specifying generic types and bounds separately is clearer:
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절 없이 직접적으로 표현될 수 없다.
  • When using a where clause is more expressive than using normal syntax. The impl in this example cannot be directly expressed without a where clause:
use std::fmt::Debug;
trait PrintInOption {
fn print_in_option(self);
}
// `T:Debug`
// , `where` :
impl<T> PrintInOption for T where
Option<T>: Debug {
// `Option:Debug`
// .
fn print_in_option(self) {
println!("{:?}", Some(self));
}
}
fn main() {
let vec = vec![1, 2, 3];
vec.print_in_option();
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

See also:

RFC, struct, and trait

results matching ""

    No results matching ""