[Pre-RFC] Early drop trait



Extending std::ops::Drop trait so that user can specify whether the object should be dropped at the end of the enclosing block(the current behavior) or as early as possible.


There are types that it’s almost always preferred to drop as early as possible, e.g., Mutex, RwLock. Those will have optimal behavior automatically.

Detailed design

Ideally I think dependent type is the best way to express this, which Rust doesn’t have yet though.

impl std::ops::Drop for Foo {
    let DROP_STRATEGY : DropStrategy = DropStrategy::Early;
    // let DROP_STRATEGY : DropStrategy = DropStrategy::Late;  // Or this.
    fn drop(&mut self) {
        // ...

The dropping timing will be controlled by Foo::DROP_STRATEGY enum value.

How We Teach This



Complicating Drop.


Using blocks {} to control drop timing.

Unresolved questions



It is a breaking change to make standard library lock guards drop earlier than they currently do.


Ignoring the breaking change issue for a moment…

In general, if I wanted a mutex to be released earlier, I would much rather type some more curly braces to make it explicit exactly when the release should happen.

Do you have a concrete example where “more curly braces” is not an option, but a “best effort drop-early policy” would help?


Mutex guards can be explicitly dropped wherever you want them to:

let x = foo.lock();
// do stuff with x
// foo is now unlocked.


Related eager drop discussion in the past: https://github.com/rust-lang/rfcs/pull/239