[solved] Does shadowing involve keeping unuseful data in memory until the end of the block? [Rust fundamentals]

Hello rust community,

Still on the fundamentals... How long a shadowed value lives in memory?

little use-case:

let my_identifier = String::from("first bindings");
{
    let my_identifier = String::from("second bindings");
    println!("{:?}", my_identifier);
}
println!("{:?}", my_identifier);
let my_identifier = String::from("third bindings");
println!("{:?}", my_identifier);
  • Option 1: Memory occupied by String::from("first bindings") is freed as soon a my_identifier is bind to another value in the same scope level!
  • Option 2: Memory occupied by String::from("first bindings") is freed at the end of the block
  • Option 3: Something else I do not know yet?

Please clarify understanding of rust!
Br,
JP

Option 2.

Ah. This means that I will keep it in memory along the way even if I can not access it anymore.

Thanks for the answer @notriddle !

No problem.

A full description of how dropping works in Rust can be found in the reference.

1 Like

Inspiring from the reference that you gave, it is crystal clear now:

struct StringWrapper {
    name: &'static str,
}

impl Drop for StringWrapper {
    fn drop(&mut self) {
        println!("> Dropping {}", self.name);
    }
}

fn main() { //Block 1
    let my_identifier = StringWrapper { name:"first bindings"};
    { //Block 2
        let my_identifier = StringWrapper { name:"second bindings"};
        println!("{:?}", my_identifier.name);
        println!("End of the block 2");
    }
    println!("{:?}", my_identifier.name);
    let my_identifier = StringWrapper { name:"third bindings"};
    println!("{:?}", my_identifier.name);
    println!("End of the block 1");
}

Gives:

"second bindings"
End of the block 2
> Dropping second bindings
"first bindings"
"third bindings"
End of the block 1
> Dropping third bindings
> Dropping first bindings
1 Like

This topic was automatically closed after 26 hours. New replies are no longer allowed.