rust-lang / rust-lang/rfcs

Potential generalization of destructing struct destructuring

Open
#713 5 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

Issue by glaebhoerl
Monday Jan 27, 2014 at 21:17 GMT

For earlier discussion, see https://github.com/rust-lang/rust/issues/11855

This issue was labelled with: in the Rust repository


Currently structs with destructors are (sensibly) not allowed to be move-destructured (#3147), because then when their destructor runs, it would access deinitialized values.

This could potentially be generalized if we recognize that a destructor, in other words drop glue, is not an indivisible thing. It consists of the Drop impl for the struct itself, and the destructors for each of its fields. Therefore if we write:

struct S { a: A, b: B }
impl Drop for S { ... }
let s = make_some_s();
let S { a, b } = s;

when the destructuring happens we could run the Drop impl for S, but not the drop glue for A and B. Those are then moved out, and their destructors will run later, whenever they go out of scope.

I believe this is sound: Drop::drop() takes &mut self, so it can mutate the components of S but not deinitialize them. If we broaden our considerations to unsafe code, then if the fields of a struct S have destructors themselves, then the Drop impl for S must, even today, leave them in a valid state, because those destructors will then access it. It is only cases where the fields of S do not have their own destructors, and the Drop impl for S uses unsafe code to put them in an invalid state, which would become dangerous, and we would have to be very careful about.

We'd obviously have to think about whether we actually want this (I haven't thought of any use cases yet), but as a theoretical possibility, I think it checks out.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the earlier discussion in Rust issue #11855, then review the proposed interaction between struct destructuring, Drop implementations, and field drop glue described here. Done would require a settled design or RFC decision that defines whether this generalization is sound and what behavior it requires.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.