Created
May 9, 2020 10:47
-
-
Save nesteruk/267f84b020ff6e94942b6d57e5cb93f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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