← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.c.2.e · 生成模型:未记录

枚举统一互斥变体

理解等级:中级

枚举把互斥的可能性声明为一个类型。每个值只处于其中一种变体,同一函数仍能接受任何变体。带数据的变体同时表明情形并约束负载类型,比如 IPv4 变体要求四个 u8,而 IPv6 可以要求地址结构。元组式变体还能用其名字构造枚举值。结构体适合组合同时存在的字段。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 枚举与模式匹配 Defining an Enum · 查看原书依据

      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 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.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第06章 枚举与模式匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c06.xhtml`,块 0025) - 结论依据:原文用两种 IP 地址的不同数据形状说明为何把字段直接放进变体。 - 原始内容: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 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.