Going over through Rust for Rustacean book and came across this example.
Why is the example wrong(as specified in the comments): Listing 1-7 gives an example of the ways in which you can move the value behind a mutable reference
fn replace_with_84(s: &mut Box<i32>) {
// this is not okay, as *s would be empty:
1 // let was = *s;
From what I understand, we are just trying to copy the value pointed by s into another variable was.
For eg. If s points to value 42 in the heap, was variable would hold value 42. I don't understand why *s would be empty as s points to integer data type which implements copy trait.
Since *s is i32 type and implements copy trait, value won't be moved and would be copied from *s to was.
Correct me if I am wrong but my understanding is s is a pointer on stack that points to value in heap.
The replace_with_84() just copies the value on heap to another variable was
4 | let was = *s;
| ^^ move occurs because `*s` has type `Box<i32>`, which does not implement the `Copy` trait
So then the question becomes, why doesn't Box<i32> implement the Copy trait? I believe it's because that statement means "copy the Box" not "copy the contents of the Box", because s is a pointer to the Box, not its contents. Things that require allocation, like Box, are duplicated using clone rather than by copying/assignment, so you know that there is a real cost.
Getting a reference to the contents of s with an &mut i32 allows us to copy it: