5

According to the Rust book, "when a binding goes out of scope, the resource that they’re bound to are freed". Does that also apply to shadowing?

Example:

fn foo() {
    let v = vec![1, 2, 3];
    // ... Some stuff
    let v = vec![4, 5, 6]; // Is the above vector freed here?
    // ... More stuff
} // Or here?
Heiko Seeberger
  • 3,702
  • 21
  • 20
  • 1
    A binding is just a name for a value, pointing the name to something else does not affect the value itself, which lives as it would have otherwise. – Matthieu M. May 18 '15 at 14:25

1 Answers1

10

No, it is not freed immediately. Let's make the code tell us itself:

struct Foo(u8);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

fn main() {
    let a = Foo(1);
    let b = Foo(2);

    println!("All done!");
}

The output is:

All done!
Dropping 2
Dropping 1

For me, this has come in handy in cases where you transform the variable into some sort of reference, but don't care about the original. For example:

fn main() {
    let msg = String::from("   hello world   \n");
    let msg = msg.trim();
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I'm confused about the first example. It declares two variables, a and b, but there's no shadowing, so I don't think it demonstrates when memory for a shadowed variable is freed. – Rob Streeting Nov 20 '22 at 10:41