简体   繁体   English

如何创建一个允许非消费和消费功能的构建器

[英]how can I create a builder which allows non-consuming and consuming functions

I want to create a builder for a struct representing an analytics event.我想为表示分析事件的结构创建一个构建器。 once the event is "sent" the builder should be consumed.一旦事件被“发送”,构建器就应该被消耗掉。

I read this primer:我读了这本入门书:

https://doc.rust-lang.org/1.0.0/style/ownership/builders.html https://doc.rust-lang.org/1.0.0/style/ownership/builders.html

so to allow simple chaining without reassignment (which might be required since there are many execution branches), my builder looks like this (simplified)所以为了允许简单的链接而不需要重新分配(因为有很多执行分支,这可能是必需的),我的构建器看起来像这样(简化)

pub struct AnalyticsEvent {

}

impl AnalyticsEvent {
  pub fn new() -> Self {
    AnalyticsEvent { }
  }
 pub fn add_property(&mut self) -> &mut AnalyticsEvent {
        self
    }

// now I want the "send" to consume the event
pub fn send(self) {
/// ....
    }
}


link to playground链接到游乐场

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fbe9e261a419608f2c592799f22ba9f9 https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=fbe9e261a419608f2c592799f22ba9f9

You can't mix both in the same chain, since your non-consuming methods only return &mut T there's no way for self -consuming methods to be called on them.你不能在同一个链中混合两者,因为你的非消费方法只返回&mut T没有办法在它们上调用self消费方法。

So either keep the builder interface as-is and replace所以要么保持构建器界面原样并替换

    event.add_property().send();

by经过

    event.add_property();
    event.send();

or change the builder interface to always work on owned objects, requiring the odd reassignment in some cases.或更改构建器界面以始终处理拥有的对象,在某些情况下需要奇怪的重新分配。

In the latter case you could mitigate the issue by adding convenience methods eg a map which would enclose the conditional situation:在后一种情况下,您可以通过添加便利方法来缓解问题,例如map将包含条件情况:

    event.add_property()
         .add_property()
         .map(|e| if condition {
             e.add_property()
         } else {
             e
         })
         .add_property()
         .send();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM