知识卡片

普通读书笔记卡 · 10504.a.6.c.1 · 生成模型:未记录

用选项类型取走字段

理解等级:中级

字段允许被取走时,可以把类型设计为 Option。例如在 Vec 中使用 Option 保存姓名,composers[0].name.take() 将旧的 Some(String) 移给调用者,并在原位置留下合法的 None;已是 None 时返回 None。它表达的是字段在业务上可以缺省,结构体和集合继续保持完整。

关联阅读:[[取出元素时保持集合有效]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第03章《Ownership and Moves》|保持集合有效地取得元素所有权,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch03.xhtml#moves-and-indexed-content` - 结论依据:原文展示对索引字段直接移动的失败,并验证 Option::take 与以 None 替换旧值的效果一致。 - 原始内容:None is a legitimate value for the field to hold, so this works: