Implement the Builder Pattern in Rust by defining a struct with private fields, a separate builder struct with public setter methods, and a build method that constructs the final instance. This approach uses the new method to initialize the builder and chaining setters to configure optional fields before finalizing the object.
struct Email {
sender: String,
subject: String,
content: String,
}
struct EmailBuilder {
sender: Option<String>,
subject: Option<String>,
content: Option<String>,
}
impl EmailBuilder {
fn new() -> Self {
EmailBuilder {
sender: None,
subject: None,
content: None,
}
}
fn sender(mut self, sender: String) -> Self {
self.sender = Some(sender);
self
}
fn subject(mut self, subject: String) -> Self {
self.subject = Some(subject);
self
}
fn content(mut self, content: String) -> Self {
self.content = Some(content);
self
}
fn build(self) -> Email {
Email {
sender: self.sender.expect("sender is required"),
subject: self.subject.expect("subject is required"),
content: self.content.expect("content is required"),
}
}
}
fn main() {
let email = EmailBuilder::new()
.sender("user@example.com".to_string())
.subject("Hello".to_string())
.content("Hi there!".to_string())
.build();
println!("Email sent from {}", email.sender);
}