Questions about deref

Hi I know this may be asked many times, if so sorry about it.

struct Foo {
    bar: String

fn main() {
    let p = &mut Foo{bar: String::from("bar")};
    *p; // what happened when try to deref it?

Can somebody explain it to me? Thanks.

Let's expand things out a little (playground):

fn oops(p: &mut Foo) {
    // Try to take ownership of the Foo behind the p pointer
    let q = *p;

fn main() {
    let mut foo = Foo { bar: String::from("bar") };
    oops(&mut foo);
    // I still own foo so this is possible:
    println!("{:?}", foo);

When you try to take ownership like in the oops function, you try to move the value in question, the Foo. But you can't move it out from behind the &mut reference, because it's still owned by something else. So you get an error.

In your example, *p; is still a move, like q = *p;. You tried to move the Foo out from behind the &mut Foo (and then immediately drop it).

1 Like

so this * operation on p, it's just move, not Copy right?

It will be copying, if the type behind the reference is Copy. Note, however, that this is a purely compile-time difference - in both cases this would be compiled down to memcpy (before optimizations).

Hi so the code under can not be complied reason is not implied Copy Trait

struct Person {
        name: String,

    impl<T: ToString> From<T> for Person {
        fn from(name: T) -> Self {
            let p = &mut Person {
                name: name.to_string(),

but *p does not mean copy it right? it simply means move out the ownership of a Person? the reason can not compile is that Person does not live long enough?

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.