知识卡片

普通读书笔记卡 · 10650.a · 生成模型:未记录

从可变借用中取走状态

理解等级:中级

方法持有 &mut Post 时,不能把某个字段移走后留下未初始化的结构体。将可消费的 state 存成 Option>,用 take 把旧值取出同时写入 None。然后把 Box 交给接收 self: Box 的转移方法,将返回的新状态写回 Some。旧状态在转移后失效,公开方法完成时状态始终存在。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0133) - 结论依据:原文解释 take 用 None 占位并移出旧值,随后把转换所得放回。 - 原始内容:To consume the old state, the request_review method needs to take ownership of the state value. This is where the Option in the state field of Post comes in: we call the take method to take the Some value out of the state field and leave a None in its place because Rust doesn’t let us have unpopulated fields in structs ❷.