简体   繁体   English

结构体和枚举的区别

[英]Difference between struct and enum

I'm confused about this statement from the Rust Book :对 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 .版本四类型的 IP 地址将始终有四个数字组件,其值介于 0 和 255 之间。如果我们想将 V4 地址存储为四个u8值,但仍将 V6 地址表示为一个String值,我们将无法使用结构 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.但是,当我尝试使用结构将 V4 地址存储为四个u8值但仍将 V6 地址表示为一个String值时,它也执行相同的操作而没有任何错误。

#[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);      
}

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;枚举:128; 64 for the largest variant and 64 for the variant identifier.最大变体为 64,变体标识符为 64。

  • Struct: 192;结构:192; aligned to 64 bits, so we have 54 bits of padding对齐到 64 位,所以我们有 54 位的填充

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.在您的情况下 - IPv4 或 IPv6。 With a structure as in your example you have to provide both V4 and v6 address.对于示例中的结构,您必须同时提供 V4 和 V6 地址。 You cannot provide only V4 or only V6.您不能只提供 V4 或只提供 V6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM