知识卡片

普通读书笔记卡 · 6074.c.3.a.2

重复构建必须重新生成对象

理解等级:中级

若同一构建器需要生成多个对象,build不能每次移走内部唯一值。build(&self)->Details需在每次调用构造新对象,例如克隆模板;目标不能Clone时则保留足够状态来重新生成。是否复制昂贵资源、复用共享句柄或重新读取时间,都应是明确选择。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Item 7: Use builders for complex types · 查看原书依据

      pub fn build(&self) -> Details { // ... } The implementation of this repeatable build() method then has to construct a fresh item on each invocation. If the underlying item implements Clone, this is easy—the builder can hold a template and clone() it for each build. If the underlying item doesn’t implement Clone, then the builder needs to have enough state t

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Item 7: Use builders for complex types》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u038-ch01-052)。 - 结论依据:原文在“pub fn build(&self)”附近的定义、例子或代码支撑本卡核心说明:若同一构建器需要生成多个对象,build不能每次移走内部唯一值。边界按已读前提解释;示例未执行。 - 原始内容:pub fn build(&self) -> Details { // ... } The implementation of this repeatable build() method then has to construct a fresh item on each invocation. If the underlying item implements Clone, this is easy—the builder can hold a template and clone() it for each build. If the underlying item doesn’t implement Clone, then the builder needs to have enough state t