Doubt in borrowing the derefrenced pointer value representation in the Book Chapter 4.2

In Chapter 4 we have an example where it says " r2 pointing to the heap value 2".
But I guess r2 actually points to borrowed derefrenced value of x i.e. ( borrow of *x )

Confirmed this with below code and compilation error:

pdawg@predator:~/rough$ cat try.rs
fn func(y: Box) {
println!("{y}");
}

fn main () {
let x: Box = Box::new(2);
let r2 = &*x;
func(x);
println!("{r2}");
}

pdawg@predator:~/rough$ rustc try.rs
error[E0505]: cannot move out of x because it is borrowed
--> try.rs:8:10
|
6 | let x: Box = Box::new(2);
| - binding x declared here
7 | let r2 = &*x;
| --- borrow of *x occurs here <<<<<<<< here
8 | func(x);
| ^ move out of x occurs here
9 | println!("{r2}");
| ---- borrow later used here

error: aborting due to 1 previous error

For more information about this error, try rustc --explain E0505.


Please let me know if I am understanding this correctly (newbie here).
Thanks in advance.

First of all, friendly reminder about code formatting.

Next, what do you actually expect from this code? When you move the non-Copy value (and Box is not Copy, since it is responsible for deallocating memory), every reference to it or to its contents is invalidated, of course, since otherwise they would point to nowhere.

&* in Rust is not two operations. Whenever possible it’s merged into a single combined operation that uses the original place of the object.

I think you're mixing two different concepts here:

  • from a memory point of view, i.e. what happens at runtime, r2 will be pointing to the heap value 2;
  • from a borrowing point of view, i.e. what the borrow checker sees when you're compiling your program, r2 is borrowing *x.
3 Likes

I'm not sure, but I think you're asking whether there is an error in the book, or it is unclear.

If it helps, I believe the two statements above are both true. r2 is pointing to the borrowed dereferenced value of x (this is called a reborrow), and is pointing to the heap value 2. The dereference is a place expression describing where 2 is stored, and the borrow gives us a pointer to that place.

If that doesn't make sense, can you describe more about what you're asking? The terminology may be confusing.

(FYI, It looks like you're using an older version of the book, because when I look at section 4.2 it uses different examples.)

1 Like

Yep, i guess that makes more sense.
thanks.

Hey, thanks. this helped.

I am using the one with the quiz.
https://rust-book.cs.brown.edu/ch04-02-references-and-borrowing.html#references-and-borrowing

Maybe i should stick to the latest.

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.