← 返回刚才阅读的位置

知识卡片

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

消耗构建器以移动字段

理解等级:高级

当 build(&self) 只借用构建器时,不能把其中的 Vec<String> 等非 Copy 值直接移进成品。改为 build(self) 后,方法拥有整个临时值,可以取走 Option<T> 内部的 T,所有字段可走相同的生成路径,也无需额外的 Clone 约束。配合 setter(mut self, value: T) -> Self,链式调用会把所有权传给下一步。

此接口把构建器当一次性中间值。要基于同一配置创建多个结果,需要另外设计复用或复制方式。移动避免了深度克隆,也可能涉及大值的字节搬运,性能以实际测量为准。

相关卡片 [[从字段生成构建器代码]]、[[AST 只能看见类型写法]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Testing a builder macro 按值接收构建器 · 查看原书依据

      But there is another, less limiting way. Our builder is a temporary struct—something to hold onto our data while the struct we want is incomplete. So moving, which we have been trying to avoid, can actually be a good thing. And the most efficient way to deal with the builder is probably to empty it. How do we go about doing this? The answer is by consuming self instead of borrowing a (mutable) reference to it.

    参考来源

    - 位置:《Write Powerful Rust Macros》第06章《Testing a builder macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-6.xhtml#p126) - 结论依据:混合字段测试触发从借用中移出 Vec 的错误,清单 6.27–6.29 改为按值接收并移出字段,随后说明复用和性能边界。 - 原始内容:But there is another, less limiting way. Our builder is a temporary struct—something to hold onto our data while the struct we want is incomplete. So moving, which we have been trying to avoid, can actually be a good thing. And the most efficient way to deal with the builder is probably to empty it. How do we go about doing this? The answer is by consuming self instead of borrowing a (mutable) reference to it.