mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-10-31 21:48:49 +00:00
48 lines
1.5 KiB
Rust
48 lines
1.5 KiB
Rust
|
// ./src/generics/phantom.md
|
||
|
|
||
|
|
||
|
use std::marker::PhantomData;
|
||
|
|
||
|
// A phantom tuple struct which is generic over `A` with hidden parameter `B`.
|
||
|
#[derive(PartialEq)] // Allow equality test for this type.
|
||
|
struct PhantomTuple<A, B>(A, PhantomData<B>);
|
||
|
|
||
|
// A phantom type struct which is generic over `A` with hidden parameter `B`.
|
||
|
#[derive(PartialEq)] // Allow equality test for this type.
|
||
|
struct PhantomStruct<A, B> { first: A, phantom: PhantomData<B> }
|
||
|
|
||
|
// Note: Storage is allocated for generic type `A`, but not for `B`.
|
||
|
// Therefore, `B` cannot be used in computations.
|
||
|
|
||
|
fn part0() {
|
||
|
// Here, `f32` and `f64` are the hidden parameters.
|
||
|
// PhantomTuple type specified as `<char, f32>`.
|
||
|
let _tuple1: PhantomTuple<char, f32> = PhantomTuple('Q', PhantomData);
|
||
|
// PhantomTuple type specified as `<char, f64>`.
|
||
|
let _tuple2: PhantomTuple<char, f64> = PhantomTuple('Q', PhantomData);
|
||
|
|
||
|
// Type specified as `<char, f32>`.
|
||
|
let _struct1: PhantomStruct<char, f32> = PhantomStruct {
|
||
|
first: 'Q',
|
||
|
phantom: PhantomData,
|
||
|
};
|
||
|
// Type specified as `<char, f64>`.
|
||
|
let _struct2: PhantomStruct<char, f64> = PhantomStruct {
|
||
|
first: 'Q',
|
||
|
phantom: PhantomData,
|
||
|
};
|
||
|
|
||
|
// Compile-time Error! Type mismatch so these cannot be compared:
|
||
|
// println!("_tuple1 == _tuple2 yields: {}",
|
||
|
// _tuple1 == _tuple2);
|
||
|
|
||
|
// Compile-time Error! Type mismatch so these cannot be compared:
|
||
|
// println!("_struct1 == _struct2 yields: {}",
|
||
|
// _struct1 == _struct2);
|
||
|
}
|
||
|
|
||
|
pub fn main() {
|
||
|
part0();
|
||
|
}
|
||
|
|