Using * to dereference custom type implemented Deref trait raise error

Viewed 45

I'm new to Rust and have been reading The Rust Programming Language but stuck at the smart pointer chapter.

With the smart pointer Box<T> from Rust stdlib, I can do this:

fn main() {
    let boxed = Box::new("text".to_string());
    let unboxed = *boxed; // equivalent to `*std::ops::Deref::deref(&boxed)`
    // let unbox_again = *boxed;
    // error: use of moved value *boxed
}

And I can see that using * to dereference a pointer will make the ownership move.

Then I followed the Define your own smart pointer example from the book, here's my code:

use std::ops::Deref;

struct MyBox<T> {
    value: T
}

impl<T> MyBox<T> {
    fn new(x: T) -> Self {
        MyBox { value: x }
    }
}

impl<T> Deref for MyBox<T>  {
    type Target = T;

    fn deref(&self) -> &Self::Target {
       &self.value 
    }
}

fn main() {
    let my_boxed = MyBox::new("string".to_string());
    let my_unboxed = *my_boxed;
    // error: move occurs here
}

I tried the same as with the first example, but I got error when I tried using * to dereference MyBox<T>.

So what's the problem with MyBox<T>?

I know that Box<T> pointer actually stores data on the heap while MyBox<T> not. Is it something related to this?

0 Answers
Related