知识卡片
构建器接收者决定使用方式
按值返回Self的构建器适合链式调用,条件分步设置后需把返回值重新赋回变量,build(self)也消耗构建器。&mut self返回&mut Self可直接分步修改,但要为后续使用绑定足够长寿的构建器,避免留下对临时值的借用。两种风格的优点不能在不改签名时同时假定成立。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 7: Use builders for complex types · 查看原书依据
The all-consuming nature of this style of builder leads to a couple of wrinkles. The first is that separating out stages of the build process can’t be done on its own: let builder = DetailsBuilder::new( "Robert", "Builder", time::Date::from_calendar_date(1998, time::Month::November, 28) .unwrap(), ); if informal { builder.preferred_name("Bob"); } let bob = b
参考来源
- 位置:《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-051)。
- 结论依据:原文在“The all-consuming nature”附近的定义、例子或代码支撑本卡核心说明:按值返回Self的构建器适合链式调用,条件分步设置后需把返回值重新赋回变量,build(self)也消耗构建器。边界按已读前提解释;示例未执行。
- 原始内容:The all-consuming nature of this style of builder leads to a couple of wrinkles. The first is that separating out stages of the build process can’t be done on its own: let builder = DetailsBuilder::new( "Robert", "Builder", time::Date::from_calendar_date(1998, time::Month::November, 28) .unwrap(), ); if informal { builder.preferred_name("Bob"); } let bob = b