如何在Rust中使用链接的方法调用编写惯用的构建模式? [英] How to write an idiomatic build pattern with chained method calls in Rust?

查看:436
本文介绍了如何在Rust中使用链接的方法调用编写惯用的构建模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下示例,可以在Rust中编写一个带有链式方法调用的构建模式,该方法可以按值或按引用传递(带有生命周期说明符)

Based on the following examples, its possible to write a build-pattern with chained method calls in Rust which either passes by value or by reference (with a lifetime specifier)

  • Is it possible to create a macro to implement builder pattern methods?
  • How to overload the 'new' method? (top answer)
  • https://github.com/rust-unofficial/patterns/blob/master/patterns/builder.md

Rust中的构建器模式可能看起来像这样:

A builder pattern in Rust may look something like this:

 ui::Button::new()
    .label("Test")
    .align(Align::Center)
    .build();

编写惯用的Rust时,有强烈的偏好吗?

When writing idiomatic Rust is there a strong preference for one over another?

在Rust中有一些很好的例子吗?

Is there some good example of how to write this in Rust?

推荐答案

实际上有两个取舍:


  • 指定的二传手应该接受自己是按值还是引用?

  • 最终的 build 方法是否应该接受 self 是按值还是参考?

  • should the named setter accept self by value or reference?
  • should the final build method accept self by value or reference?

我的建议是:


  • 设置器的可变引用

  • build 方法的值

  • mutable reference for the setters
  • value for the build method

这与 Rust Book中介绍的Builder Pattern ,该模型在 build 中使用了引用。

This differs slightly from the Builder Pattern presented in the Rust Book which uses a reference in build.

为什么通过可变参考传递二传手?

尽管编译器可以优化了对调用 fn label(self,& str)->所引起的移动。 ButtonBuilder ,它不能保证。

While a compiler may optimize away the moves caused by a call to fn label(self, &str) -> ButtonBuilder, it is not guaranteed.

另一方面,可变引用方式已经是最优的,因此您不必依赖优化器。

On the other hand, the mutable reference way is already optimal so that you need not rely on the optimizer.

为什么要按值传递最终的版本

对于仅由 Copy 字段组成的构建器,<$ c之间没有区别$ c>构建接受自我& self

For builders only composed of Copy fields, there is no difference between build taking self or &self.

但是,一旦构建器包含非 Copy 字段,就会传递& self build 需要深度克隆这些字段。

However, as soon as the builder contains non-Copy fields, passing &self to build requires deep-cloning these fields.

另一方面,传递 self 按值允许 build 移动字段,避免不必要的复制。

On the other hand, passing self by value allows build to move the fields, which avoid unnecessary copies.

如果希望重复使用构建器,则构建器应实施 Clone

If one wishes to re-use the builder, then the builder should implement Clone.

这篇关于如何在Rust中使用链接的方法调用编写惯用的构建模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆