【发布时间】:2022-01-21 06:37:03
【问题描述】:
到目前为止,我已经在官方 Rust 代码和其他 crate 中看到了两种构建器模式:
impl DataBuilder {
pub fn new() -> DataBuilder { ... }
pub fn arg1(&mut self, arg1: Arg1Type) -> &mut Builder { ... }
pub fn arg2(&mut self, arg2: Arg2Type) -> &mut Builder { ... }
...
pub fn build(&self) -> Data { ... }
}
impl DataBuilder {
pub fn new() -> DataBuilder { ... }
pub fn arg1(self, arg1: Arg1Type) -> Builder { ... }
pub fn arg2(self, arg2: Arg2Type) -> Builder { ... }
...
pub fn build(self) -> Data { ... }
}
我正在编写一个新的 crate,但我有点困惑我应该选择哪种模式。我知道如果我以后更改一些 API 会很痛苦,所以我想现在就做出决定。
我理解它们之间的语义差异,但在实际情况下我们应该更喜欢哪一个?或者我们应该如何选择它们?为什么?
【问题讨论】:
-
FWIW,
derive_builder板条箱列出了一些优点和缺点:docs.rs/derive_builder/latest/derive_builder/#builder-patterns。
标签: design-patterns rust ownership