LukeShortCloud / rootpages

Root Pages is a collection of easy-to-reference tutorials and guides primarily for Linux and other UNIX-like systems.
Other
56 stars 6 forks source link

[programming][rust] Explain empty structs and enums #963

Closed LukeShortCloud closed 1 year ago

LukeShortCloud commented 1 year ago

""" They're actually quite different, and both have their uses. Let's say you have these:

struct Foo{};

enum Bar{};

What kind of values does Foo have? Actually only a single value is possible: Foo{}; . Such a type with only one value is called a Zero-Sized Type(ZST).

What about Bar? Turns out you actually can not construct any instance of it. The only way (outside of unsafe code) to make an instance of an enum is to name a variant. Since there are no variants, you can never have a value of this enum (in fact, if you do produce one using unsafe code, it's UB). This is called an "uninhabited type".

For more info, see here: https://doc.rust-lang.org/nomicon/exotic-sizes.html """

https://www.reddit.com/r/rust/comments/91mgqk/comment/e2z75l9/?utm_source=share&utm_medium=web3x https://www.reddit.com/r/rust/comments/91mgqk/empty_enum_vs_empry_struct/