12.8 Phantom type parameters

유령 타입 매개자는 실행간에 노출되지 않는 존재지만, 정적으로(그리고 오직) 컴파일 시에 검증된다.

데이터 타입이 사용할 수 있는 확장 제네릭 타입 매개자는 마커로서 동작하거나 컴파일 시에 타입 체킹을 한다. 이들 확장 매개자들은 저장되는 값을 보유하지 않고 없고 실행 간에 동작도 없다. Data types can use extra generic type parameters to act as markers or to perform type checking at compile time. These extra parameters hold no storage values, and have no runtime behavior.

다음 예제에서, 우리는 std::marker::PhantomData에 유령 타입 매개자 개념을 혼합하여 서로 다른 데이터 타입을 포함하는 튜플을 만들고자 한다. In the following example, we combine std::marker::PhantomData with the phantom type parameter concept to create tuples containing different data types.

use std::marker::PhantomData;

// 숨겨진 매개변수 `B`를 가진 `A`에 제네릭인 유령 타입 튜플.
#[derive(PartialEq)] // 이 타입에 동일성 테스트를 허용한다.
struct PhantomTuple<A, B>(A,PhantomData<B>);

// 숨겨진 매개변수 `B`를 가진 `A`에 제네릭인 유령 타입 구조체
#[derive(PartialEq)] // Allow equality test for this type.
struct PhantomStruct<A, B> { first: A, phantom: PhantomData<B> }

// 참고 : 저장 공간은 제네릭 타입 `A`를 위해서는 할당되지만 `B`에는 되지 않는다.
// 그러므로 `B`는 계산에 사용될 수 없다.

fn main() {
    // 여기서 `f32`와 `f64`는 숨겨진 파라미터입니다.
    // PhantomTuple 타입은``로 지정됩니다.
    let _tuple1: PhantomTuple<char, f32> = PhantomTuple('Q', PhantomData);
    // PhantomTuple 타입은``로 지정됩니다.
    let _tuple2: PhantomTuple<char, f64> = PhantomTuple('Q', PhantomData);

    //``로 지정된 타입.
    let _struct1: PhantomStruct<char, f32> = PhantomStruct {
        first: 'Q',
        phantom: PhantomData,
    };
    //``로 지정된 타입.
    let _struct2: PhantomStruct<char, f64> = PhantomStruct {
        first: 'Q',
        phantom: PhantomData,
    };

    // 컴파일 타임 오류! 타입이 일치하지 않아 비교될 수 없다.
    //println!("_tuple1 == _tuple2 yields: {}",
    //          _tuple1 == _tuple2);

    // 컴파일 타임 오류! 타입이 일치하지 않아 비교될 수 없다.
    //println!("_struct1 == _struct2 yields: {}",
    //          _struct1 == _struct2
}

See also:

Derive, struct, and TupleStructs

results matching ""

    No results matching ""