Is the resource of a shadowed variable binding freed immediately?

前端 未结 1 2082
抹茶落季
抹茶落季 2020-12-12 01:09

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:



        
相关标签:
1条回答
  • 2020-12-12 01:34

    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();
    }
    
    0 讨论(0)
提交回复
热议问题