知识卡片

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

联合体读取依赖存储类型

理解等级:中级

union 以同一片存储为多个可能的字段提供表示,常见于调用 C 接口。读取时必须确保当前数据可以解释为被读取字段所声明的类型;Rust 无法仅凭字段名判断最近写入的是哪一种表示。需要安全抽象时,可以把有效字段对应的状态保留在受控接口内。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 高级特性 Using extern Functions to Call External Code · 查看原书依据

      The final action that works only with unsafe is accessing fields of a union. A union is similar to a struct, but only one declared field is used in a particular instance at one time. Unions are primarily used to interface with unions in C code. Accessing union fields is unsafe because Rust can’t guarantee the type of the data currently being stored in the union instance.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0112) - 结论依据:原文把联合体字段访问与 C 互操作联系起来,并说明编译器不能保证内部当前保存的数据类型。 - 原始内容:The final action that works only with unsafe is accessing fields of a union. A union is similar to a struct, but only one declared field is used in a particular instance at one time. Unions are primarily used to interface with unions in C code. Accessing union fields is unsafe because Rust can’t guarantee the type of the data currently being stored in the union instance.