Marker Structs
PhantomData และ marker types
PhantomData Basics
Section titled “PhantomData Basics”use std::marker::PhantomData;
fn main() { // PhantomData is zero-sized println!("Size of PhantomData<i32>: {}", std::mem::size_of::<PhantomData<i32>>()); println!("Size of PhantomData<String>: {}", std::mem::size_of::<PhantomData<String>>());
// Usage: tell compiler about logical ownership struct Container<T> { data: *const T, // Raw pointer - no ownership info _marker: PhantomData<T>, // Adds ownership/lifetime info }
impl<T> Container<T> { fn new(data: &T) -> Self { Container { data: data as *const T, _marker: PhantomData, } } }
let value = 42; let container = Container::new(&value); println!("Container created");
// Size remains same as just pointer println!("\nSize of Container<i32>: {}", std::mem::size_of::<Container<i32>>()); println!("Size of *const i32: {}", std::mem::size_of::<*const i32>());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google