← 返回起始笔记位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.4.a.3.a.1 · 生成模型:GPT-6

借用字段避免部分移动

理解等级:中级

从结构体的非 Copy 字段取走所有权会产生部分移动。原书中 steal(car.gps) 把 String 移入函数后,同一个 car 已无法作为整体传给 Debug 打印,尚未移动的 infotainment 仍能读取。若只需查看一个字段,借用它即可维持整体可用。若确实要交出拥有的值,克隆保持原值但可能增加成本。可选字段还能用 Option::take 将当前值移出,同时放回 None,留下仍然有效的结构体。

在宏里可用 let name = &ast.ident; 读取结构体名,使 ast 仍能作为完整的语法节点输出。

相关卡片 [[扩展时重发原结构体]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第05章《Hiding information and creating mini-DSLs with function-like macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-5.xhtml#p33) - 结论依据:第 5.1.2 节的 Car 偷取例、Option::take 对照和重新输出 DeriveInput 的写法体现了同一所有权机制。 - 原始内容:But how can I print the GPS when someone already stole—and dropped—it?” Regretfully, the compiler is right: ownership of a part of the struct has been moved—meaning the struct can no longer be used, though we can still retrieve (and, for example, print) any values that haven’t moved yet, like infotainment. A simple solution for avoiding partial moves is to clone. If we create a clone of car and