← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.f.1.h · 生成模型:未记录

枚举承载异质元素

理解等级:中级

需要存储整数、浮点数和文本等有限集合时,可把它们分别放入一个枚举的变体,再保存 Vec<枚举>。编译器能确定单一元素类型的布局,match 也能检查是否覆盖所有负载形态。面对无法预先列举的类型集合,需要其他抽象,例如 trait 对象。

相关卡片 [[枚举统一互斥变体]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第08章 常用集合(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c08.xhtml`,块 0058) - 结论依据:原文把编译期元素大小与穷尽处理联系起来,说明枚举为何适合固定的形态集合。 - 原始内容:Rust needs to know what types will be in the vector at compile time so it knows exactly how much memory on the heap will be needed to store each element. We must also be explicit about what types are allowed in this vector.