'Rust: Is an Enum a subset of Structs?

I've just learned that an Enum can be initialized with a custom data type.

Wouldn't that make Enums a subset of Structs? An Enum could be a Struct with a single unnamed variable which is initialized once and cannot be changed (like final variables in Java). Also, no methods can be implemented to enums.

Like this:

enum E {
  ONE(String)
}

struct S {
  one: String
}

Thus, in memory, both a single variable struct and enum would look the same.

Is this true or am I missing something?



Solution 1:[1]

It's actually the opposite: structs are subsets of enums. Any struct can be represented as one-variant enum:

struct Record { ... }
struct TupleLike(...);

enum Record { Variant { ... } }
enum TupleLike { Variant(...) }

This enum will even have the same in-memory representation! (though it isn't guaranteed).

On the other hand, enums with multiple variants cannot be described precisely as structs. They are usually implemented as tagged unions, for example:

enum E {
    S(String),
    I(i32),
}
E::I(123);

type E_Discriminant = u8;
const E_S: E_Discriminant = 0;
const E_I: E_Discriminant = 1;
union E_Payload {
    s: String,
    i: i32,
}
struct E {
    discriminant: E_Discriminant,
    payload: E_Payload,
}
E { discriminant: E_I, payload: E_Payload { i: 123 } };

But even doing that manually will not provide you the whole language experience of using enums: you will unable to use pattern matching, accessing variants will be unsafe (and dangerous), etc..

However, when only one variant is needed, structs are more comfortable to use, and that's why they're there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1