cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
506 stars 82 forks source link

Add a note on shadowing to chapter 4? #87

Open Tomer-Eliahu opened 1 year ago

Tomer-Eliahu commented 1 year ago

Maybe it is worth adding a note on shadowing somewhere in chapter 4.

Specifically, that when you are shadowing a variable with heap data, the old variable still exists in memory but is inaccessible.

fn main() {
let s = String::from("Hello");
let s_ref = &s;
let s = String::from("world");
println!("{s_ref}"); //prints Hello 
}

I think it worth mentioning with regards to ownership rules. In particular that the Box heap data is not deallocated when s is shadowed but rather at the end of the function.

fn main() {
let s = Box::new(2);
let s = String::from("hello"); 
// the old instance of s which is Box::new(2) is **still** in memory but inaccessible.
// It will be dropped according to the normal ownership rules. 
//That is when the scope ends the heap data of the Box
// will be deallocated as its owner (the old instance of s) goes out of scope.
}
willcrichton commented 1 year ago

This is a nice idea. I will consider where it would make sense adding it to the book.