Making Drop more magic to make it less magic

Soundness, safety and correctness are of course most important.

I’m also against performing some analysis on a fn body, that feels brittle.

As stated in the original thread, I think that both drop(&mut self), as well as the ability to re-use the fields of a struct have their valid use cases.

How is drop and field-reuse different:

drop(&mut self) gives us the ability to do some final work with the still fully operational and alive instance of that struct.

Field-reuse allows us to use parts of the no longer existent struct for something else.

Do not change Drop, but add better field-reuse

Personally, I’d like to keep Drop exactly as it is.

On top of that, I proposed to add the (optional) possibility to instruct the compiler to pass a sub-set of the fields of the no longer existent struct to a function of my choice.

What is possible in today’s Rust?

As proposed here one can use a derive to achieve almost everything in today’s Rust (please forgive possibly bad naming, it’s a first rough prototype):

#[derive(RescueOnDrop)]
#[rescue_with="FileCell::recycle"]

struct FileCell {

  // NOTE  Sadly, I have to spell out `ManuallyDrop` here:
  #[rescue_me]  file: ManuallyDrop<File>,
  #[rescue_me]  sender: ManuallyDrop<Sender<File>>,

  this_will_not_be_rescued: UnimportantType,
}

impl FileCell {
  fn recycle(file: File, sender: Sender<File>) {
    sender.send(file).unwrap();
  }
}

I’ve implemented a first very rough derive and I’m very happy with it, except that I have to spell out ManuallyDrop in the declaration of the struct FileCell, and therefore also have to manually spell out ManuallyDrop::new(...).

I could let the proc macro insert the ManuallyDrop in the field declaration, but that’s not nice either.

What could be slightly improved IMHO

With a bit more integration into the language, I should be able to declare the struct simply as:

#[derive(RescueOnDrop)]
#[rescue_with="FileCell::recycle"]

struct FileCell {
  #[rescue_me]  file: File,
  #[rescue_me]  sender: Sender<File>,
  this_will_not_be_rescued: UnimportantType,
}

Sure, I can achieve moving out of self via ManuallyDrop. It works. But, I personally feel that the ability to rescue fields from a struct instead of discarding them would be fundamental enough to deserve better support in the compiler.