简体   繁体   English

如何防止非消耗性构建器模式的移动?

[英]How to prevent move in non-consuming builder pattern?

I am trying to create a struct with non-consuming builder pattern like this:我正在尝试创建一个具有非消耗性构建器模式的结构,如下所示:

#[derive(Default)]
struct Person {
    first_name: String,
    last_name: String,
}

impl<'a> Person {
    pub fn first_name(&'a mut self, name: &str) -> &'a mut Self {
        self.first_name = name.to_owned();
        self
    }
    pub fn last_name(&'a mut self, name: &str) -> &'a mut Self {
        self.last_name = name.to_owned();
        self
    }

    pub fn greet(&self) -> String {
        format!("{:?} {:?}", self.first_name, self.last_name)
    }

    pub fn build(self) -> Self {
        self
    }
}

fn main() {
    let person = Person::default()
        .first_name("John")
        .last_name("Doe")
        .build();

    let name = person.greet();
}

But when I use build() to get the value back, I get a move error like this:但是当我使用build()取回值时,我收到如下移动错误:


error[E0507]: cannot move out of a mutable reference
  --> builder/src/main.rs:27:18
   |
27 |       let person = Person::default()
   |  __________________^
28 | |         .first_name("John")
29 | |         .last_name("Doe")
30 | |         .build();
   | |________________^ move occurs because value has type `Person`, which does not implement the `Copy` trait

How can I use a non-consuming builder pattern while ensuring my code can work in multiple lines?如何在确保我的代码可以在多行中工作的同时使用非消耗性构建器模式? Should I ditch the build() method?我应该放弃build()方法吗?

I think you should use two struct, a PersonBuilder, and a Person.我认为您应该使用两个结构,一个 PersonBuilder 和一个 Person。 The PersonBuilder can collect the applicable info and its build method can check whether a complete Person can be built, and if so return a Person by moving its info into a new Person. PersonBuilder 可以收集适用的信息,它的构建方法可以检查是否可以构建一个完整的 Person,如果可以,则通过将其信息移动到一个新的 Person 来返回一个 Person。

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

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