Last active
March 20, 2020 18:16
-
-
Save NebulaFox/8222ec0676cc3ba8aefcf6d001215c65 to your computer and use it in GitHub Desktop.
lazy loading solution
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
struct Context { | |
foo: String, | |
bar: String | |
} | |
struct ContextBuilder { | |
foo: Option<String>, | |
bar: Option<String> | |
} | |
impl ContextBuilder { | |
fn new() -> Self { | |
ContextBuilder { | |
foo: None, | |
bar: None | |
} | |
} | |
fn load_foo(mut self) -> Self { | |
if self.foo.is_none() { | |
let message = String::from("foo"); | |
self.foo = Some(message); | |
} | |
self | |
} | |
fn load_bar(mut self) -> Self { | |
if self.bar.is_none() { | |
let message = String::from("bar"); | |
self.bar = Some(message); | |
} | |
self | |
} | |
fn build_context(self) -> Context { | |
let r = self.load_foo() | |
.load_bar(); | |
Context { | |
foo: r.foo.unwrap(), | |
bar: r.bar.unwrap() | |
} | |
} | |
} | |
fn print(context: &Context) { | |
let foo = &context.foo; | |
let bar = &context.bar; | |
println!("{}{}", foo, bar); | |
} | |
fn main() { | |
let context = ContextBuilder::new() | |
.build_context(); | |
print(&context); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment