知识卡片
逆序生成类型状态转移
生成构建器状态转移时,可从最后一个字段逆序处理。第一次生成让最后一个 setter 返回 Builder<FinalBuilder>。每次保存刚处理的字段,下一轮就可用它为当前 setter 设置返回类型。由于返回类型的泛型参数变了,setter 需构造新实例,并把先前保存的值移进去。实施时可先写出一个手工的目标展开,再逐块生成标记、入口与转换,使用正向调用及遗漏字段的编译失败样例检验。书中的初始实现假定至少有一个字段,生成前还需显式处理空输入。
相关卡片 [[构建器用类型强制填字段]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Builder with attributes 生成有状态的构建器 · 查看原书依据
Because we set the previous_field in both branches of the condition, every subsequent call will end up in the if branch. Here, like before, we want to generate a setter for the current generic.
参考来源
- 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p146)
- 结论依据:8.5.2 用反向字段遍历得到下一个标记,随后用构造新泛型实例解释 why 不能原样返回 self。
- 原始内容:Because we set the previous_field in both branches of the condition, every subsequent call will end up in the if branch. Here, like before, we want to generate a setter for the current generic.