Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...