Skip to content

Instantly share code, notes, and snippets.

@nesteruk
Created May 9, 2020 10:47
Show Gist options
  • Save nesteruk/267f84b020ff6e94942b6d57e5cb93f6 to your computer and use it in GitHub Desktop.
Save nesteruk/267f84b020ff6e94942b6d57e5cb93f6 to your computer and use it in GitHub Desktop.
#[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