Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between struct and enum

Tags:

rust

I'm confused about this statement from the Rust Book:

There’s another advantage to using an enum rather than a struct: each variant can have different types and amounts of associated data. Version four type IP addresses will always have four numeric components that will have values between 0 and 255. If we wanted to store V4 addresses as four u8 values but still express V6 addresses as one String value, we wouldn’t be able to with a struct. Enums handle this case with ease:

#![allow(unused_variables)]
fn main() {
    enum IpAddr {
        V4(u8, u8, u8, u8),
        V6(String),
    }

    let home = IpAddr::V4(127, 0, 0, 1);

    let loopback = IpAddr::V6(String::from("::1"));
}

But when I tried it with structs to store V4 addresses as four u8 values but still express V6 addresses as one String value its also doing the same without any errors.

#[derive(Debug)]
struct IpAddr {
    V4:(u8, u8, u8, u8),
    V6:String,
}

fn main () {
    let home = IpAddr {
        V4: (127, 1, 1, 1), 
        V6: String::from("Hello"),
    };
    println!("{:#?}", home);      
}
like image 379
Muhammad Areeb Siddiqui Avatar asked Jan 23 '26 22:01

Muhammad Areeb Siddiqui


1 Answers

It's not the same. All enum elements have the very same size! The size of an enum element is the size of the largest variant plus the variant identifier.

With a struct it's a bit different. If we ignore padding, the size of the struct is the sum of the sizes of its members. With padding it will be a bit more:

fn main() {
    let size = std::mem::size_of::<TheEnum>();
    println!("Enum: {}", size * 8);

    let size = std::mem::size_of::<TheStruct>();
    println!("Struct: {}", size * 8);
}

struct TheStruct {
    a: u64,
    b: u8,
    c: u64
}

enum TheEnum {
    A(u64),
    B(u8),
    C(u64)
}

Here we can see the difference:

  • Enum: 128; 64 for the largest variant and 64 for the variant identifier.

  • Struct: 192; aligned to 64 bits, so we have 54 bits of padding

Another difference is in the way you use enums and structures. In an enum, you have to initialize only one of the variants. In your case - either IPv4 or IPv6. With a structure as in your example you have to provide both V4 and v6 address. You cannot provide only V4 or only V6.

like image 85
Svetlin Zarev Avatar answered Jan 25 '26 19:01

Svetlin Zarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!