How could I emulate phantomData in DROPCK CONTEXT

⚓ Rust    📅 2025-08-14    👤 surdeus    👁️ 3      

surdeus

Hello, I have been working with Rust for some time, but have never got to work very smoothly with it. Now I want to emulate a dropck case in Rust playground where I can show how phantomData can be useful, but simply by checking threads on this topic here not very straighforaward e.g. below no good code to show:

What unsoundness can be caused by destructor without PhantomData? - help - The Rust Programming Language Forum

Is PhantomData useless to dropck now? - help - The Rust Programming Language Forum

My code is hereunder ..having no idea how to add phantomData into the struct, but before that I got complain like this, I will be appreciated if you could help me to check on that, with many thanks in advance!

Blockquote

wechat_2025-08-14_084431_791

use std::ops::Deref;
use std::ptr::NonNull;

#[derive(Debug)]
struct MyPointer<T> {
    inner: NonNull<T>,
    len: i32,
    cap: i32,
}

impl<T> MyPointer<T> {
    fn new() -> Self {
        let inner = Box::new(1);
        MyPointer {
            inner: unsafe { NonNull::new_unchecked(Box::into_raw(inner)) },
            len: 7,
            cap: 8,
        }
    }
}

impl<T> Drop for MyPointer<T> {
    fn drop(&mut self) {
        let inner = unsafe { Box::from_raw(self.inner.as_ptr()) };
        drop(inner)
    }
}

impl<T> Deref for MyPointer<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { self.inner.as_ref() }
    }
}

fn main() {
    let my_ptr = MyPointer::new();
    let my_inner: i32 = unsafe { *my_ptr.inner.as_ref() };
    println!("This is instance: {:?}", &my_ptr);
    println!("This is inner: {:?}", my_inner);
}

1 post - 1 participant

Read full topic

🏷️ Rust_feed