vague
1
use std::mem::size_of;
fn main() {
dbg!(size_of::<String>(), size_of::<A>(), size_of::<C>()); // same size
}
pub enum A {
X(String),
Y(B), // adding a fieldless enum won't increase size of A
}
pub enum B {
B1, B2, B3
}
pub enum C {
X(String),
Y(D), // adding a nested fieldless enum won't increase size of C
}
pub enum D {
B(B),
E(E),
}
pub enum E {
E1, E2, E3, E4
}
The niche seems undocumented in Enums - Unsafe Code Guidelines Reference .
kpreid
2
That's because UCG tells you what you can rely on.
Option-like enums where the payload defines at least one niche value are guaranteed to be represented using the same memory layout as their payload.
Notice the word “guaranteed”. The compiler additionally optimizes enums in the way you've noticed, but it doesn't guarantee to do so.
2 Likes
vague
3
Based on the context of the quote, I think the niche in OP is called discriminant elision on Option-like enum?
kpreid
4
No; it defines an option-like enum as
Definition. An option-like enum is a 2-variant enum
where:
- the
enum
has no explicit #[repr(...)]
, and
- one variant has a single field, and
- the other variant has no fields (the "unit variant").
Your A
and C
enums have two variants, but in both cases the second variant does have fields. So, it is not option-like.
I don't think there is a name, more specific than just the general "niche optimization", for your case.
1 Like
system
Closed
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.