Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

rust - Is the resource of a shadowed variable binding freed immediately?

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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   
");
    let msg = msg.trim();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...