Jason Yu
Jason Yu

Reputation: 2038

Is it available to drop a variable holding a primitive value in Rust?

Updated Question:

Or I can ask this way: for every type T, if it's Copy, then there is no way for it to be moved, right? I mean is there any way like the std::move in C++ can move a copyable value explicitly?


Original Question:

Presume we have below a piece of Rust code, in this code, I defined a variable x holding an i32 value. What I want to do is to drop its value and invalidate it. I tried to use ptr::drop_in_place to drop it through a pointer, but it doesn't work, why?

fn main() {
    let mut x = 10;
    use std::ptr;
    unsafe {
        ptr::drop_in_place(&mut x as *mut i32);
    }
    println!("{}", x);  // x is still accessible here.
}

Upvotes: 1

Views: 497

Answers (1)

kmdreko
kmdreko

Reputation: 60457

For every type T, if it's Copy, then there is no way for it to be moved, right?

That is one way to word it. The semantics of Copy are such that any move leaves the original object valid.

Because of this, and that Drop and Copy are mutually exclusive traits, there's no way to "drop" a Copy. The traditional method of calling std::mem::drop(x) won't work. The only meaningful thing you can do is let the variable fall out of scope:

fn main() {
    {
        let x = 10;
    }
    println!("{}", x);  // x is no longer accessible here.
}

I mean is there any way like the std::move in C++ can move a copyable value explicitly?

The specifics of copying vs moving are quite different between C++ and Rust. All types are moveable in Rust, whereas its opt-in for C++. And moving and copying in Rust are always bitwise copies, there's no room for custom code. Moving in Rust leaves the source object invalid whereas its still useable as a value in C++.

I can go on, but I'll leave off one last bit: moving a primitive in C++ isn't different than a copy either.

Upvotes: 3

Related Questions