Borrowing in rust

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

1 Like

Here is the error:

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:

    let s1: &mut i32 = &mut s;
    let was: i32 = *s1;

s is a &mut Box<i32>, and *s is a Box<i32> (and **s is an i32). Box<i32> is not Copy -- you can clone, but that doesn't happen automatically.

So this:

let was = *s;

is trying to move the Box<i32> from behind the &mut Box<i32>, not copy it. You can read more about the difference here.

Whereas this:

    let was = **s;

can copy the i32.


 &mut Box<i32>          Box<i32>               i32
+---+---+---+---+      +---+---+---+---+      +---+---+
| Pointer       | ---> | Pointer       | ---> | data  |
+---+---+---+---+      +---+---+---+---+      +---+---+
 s                      *s                     **s
7 Likes