Why does the following code compile successfully?

fn main() {

let mut x = Box::new(10);

let mut v = Vec::new();

v.push(x.as_mut() as *mut i32);


let _z = unsafe { Box::from_raw(*v.get(0).unwrap()) };

println!("{}", v.len());


Because you used unsafe, which is telling the compiler to trust you. It's undefined behavior (UB) though (run Miri under Tools), that is, very buggy incorrect code.



Why the drop check of PhantomData doesn't work?

    fn main() {

        use std::marker::PhantomData;

        struct Bar(u8);

        impl Drop for Bar {
            fn drop(&mut self) {
                println!("drop Bar")

        struct Foo<T> {
            handler: *mut T,
            resource_type: PhantomData<T>,

        impl<T> Drop for Foo<T> {
            fn drop(&mut self) {
                println!("drop Foo");

        let mut bar = Box::new(Bar(9));
        let foo = Foo::<Bar> {
            handler: bar.as_mut() as *mut _,
            resource_type: PhantomData,
        println!("{:p}", foo.handler);

I expect the drop check to work after using PhantomData. Thank you for your reply

Please specify what's you expectation. (and format your code).

"Drop check" is commonly misunderstood. It doesn't help with associating one piece of data with another one, you'll need lifetimes for that.

In fact, PhantomData fields in structs will (almost) never do anything for you w.r.t. drop check, if you aren't using the unstable dropck_eyepatch feature.

By the way, you can get syntax highlighting by using ``` code fences instead of indentation. See Forum Code Formatting and Syntax Highlighting

Thanks! this is my first time to use.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.