Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#[derive(Debug)]
struct Person
{
name: String,
position: String
}
impl Default for Person
{
fn default() -> Self {
Person{
name: "".to_string(),
position: "".to_string() }
}
}
struct FunctionalBuilder<TSubject>
where TSubject : Default
{
actions: Vec<Box<dyn Fn(&mut TSubject) -> ()>>
}
impl<TSubject> FunctionalBuilder<TSubject>
where TSubject : Default
{
fn build(self) -> TSubject
{
let mut subj = TSubject::default();
for action in self.actions
{
(*action)(&mut subj);
}
subj
}
fn new() -> FunctionalBuilder<TSubject>
{
Self {
actions: Vec::new()
}
}
}
struct PersonBuilder
{
builder: FunctionalBuilder::<Person>
}
impl PersonBuilder
{
pub fn new() -> Self {
PersonBuilder { builder: FunctionalBuilder::<Person>::new() }
}
pub fn called(mut self, name: &str) -> PersonBuilder
{
let value = name.to_string();
self.builder.actions.push(Box::new(move |x| {
x.name = value.clone();
}));
self
}
pub fn build(self) -> Person
{
self.builder.build()
}
}
pub fn demo()
{
let builder = PersonBuilder::new();
let me = builder
.called("Dmitri")
.build();
println!("{:?}", me);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.