Underscore expression and the drop order

⚓ Rust    📅 2025-05-01    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 112 days ago. The information described in this article may have changed.

Hello everyone.

Rust got me bamboozled again.

So I have this code:

struct Droppable;

impl Drop for Droppable {
    fn drop(&mut self) {
        println!("dropping");
    }
}

struct S {
    droppable: Droppable,
}

and two test functions:

fn test1() {
    println!("test1");
    let s = S { droppable: Droppable };
    {
        {
            let S { droppable: _ } = s;
        };
        println!("should be dropped?");
    }
    println!("end of test1");
}

fn test2() {
    println!("test2");
    let s = S { droppable: Droppable };
    {
        {
            let S { droppable: _droppable } = s;
        };
        println!("should be dropped?");
    }
    println!("end of test2");
}

The only difference between them is the destructuring of s: it's let S { droppable: _ } = s in the first case and let S { droppable: _droppable } = s in the second.

The second case behaves as I expect it to and droppable is dropped in the same block where s is destructured. I.e. i get

test2
dropping
should be dropped?
end of test2

But in the first case it's dropped at the end of the function.

test1
should be dropped?
end of test1
dropping

Here is the full code on playground.

This was very surprising and I actually had a bug because of it, because my real-world droppable needed to be dropped early.
But now I'm wondering why it works like this. I've read the chapter about destructors in the docs and couldn't find any explanation for this. Did I miss something?

4 posts - 3 participants

Read full topic

🏷️ rust_feed