Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

convention - How to write an idiomatic build pattern with chained method calls in 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)

A builder pattern in Rust may look something like this:

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are actually two trade-offs:

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

My recommendation is:

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

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


Why passing by mutable reference for the setters?

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.


Why passing by value for the final build?

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...