Skip to content

Commit f09d7e5

Browse files
committed
add an unresolved question
1 parent e735b31 commit f09d7e5

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

reference/src/layout/enums.md

+52
Original file line numberDiff line numberDiff line change
@@ -346,3 +346,55 @@ enum Enum1<T> {
346346
Absent2,
347347
}
348348
```
349+
350+
## Unresolved questions
351+
352+
### Layout of single variant enums
353+
354+
[Issue #79.](https://github.com/rust-rfcs/unsafe-code-guidelines/issues/79)
355+
356+
Enums that contain a **single variant** and which do not have an
357+
explicit `#[repr]` annotation are an important special case. Since
358+
there is only a single variant, the enum must be instantiated with
359+
that variant, which means that the enum is in fact equivalent to a
360+
struct. The question then is to what extent we should **guarantee**
361+
that the two share an equivalent layout, and also how to define the
362+
interaction with uninhabited types.
363+
364+
As presently implemented, the compiler will use the same layout for
365+
structs and for single variant enums (as long as they do not have a
366+
`#[repr]` annotation that overrides that choice). So, for example, the
367+
struct `SomeStruct` and the enum `SomeEnum` would have an equivalent
368+
layout ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3697ac684c3d021892694956df957653))::
369+
370+
```rust
371+
struct SomeStruct;
372+
enum SomeEnum {
373+
SomeVariant,
374+
}
375+
```
376+
377+
Similarly, the struct `SomeStruct` and the enum `SomeVariant` in this
378+
example would also be equivalent in their layout
379+
([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=924724764419f846c788a8763da45992)):
380+
381+
```rust
382+
struct SomeStruct { x: u32 }
383+
enum SomeEnum {
384+
SomeVariant { x: u32 },
385+
}
386+
```
387+
388+
In fact, the compiler will use this optimized layout even for enums
389+
that define multiple variants, as long as all but one of the variants
390+
is uninhabited
391+
([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3cc1484c5b91097f3dc2015b7c207a0e)):
392+
393+
```rust
394+
struct SomeStruct { x: u32 }
395+
enum SomeEnum {
396+
SomeVariant { x: u32 },
397+
UninhabitedVariant { y: Void },
398+
}
399+
```
400+

0 commit comments

Comments
 (0)