Enums and empty structs

#1
struct Ipv4Addr
{
    // --snip--
}

struct Ipv6Addr
{
    // --snip--
}

enum IpAddr
{
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}

How can you put any data types you want (Strings, integers, floats etc) into V4 and V6 when these structs are literally empty?
https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html

0 Likes

#2

They’re only empty in the initial example in that chapter. In the part you’ve quoted, it’s using the tuple struct form to declare that the V4 variant must contain an Ipv4Addr. Listing 6-2 also shows that enum variants can be defined like named-field structs, but this is less common.

0 Likes

#3

So generally you are supposed to put in data types in the structs, right?

0 Likes

#4

If you want it to be functional as a standalone type, then yes, define it on its own struct and then use that for the contents of the enum variant. Here you can directly pass around a value of Ipv4Addr, and it has its own methods and trait implementations, etc. If you never need that, then you can do it all directly in the enum.

(I vaguely recall some RFC automatically treating enum variants as a standalone type too.)

1 Like