Skip to content

Instantly share code, notes, and snippets.

@NebulaFox
Last active March 20, 2020 18:17
Show Gist options
  • Save NebulaFox/897a513604a9612597e9ebc5d31bd624 to your computer and use it in GitHub Desktop.
Save NebulaFox/897a513604a9612597e9ebc5d31bd624 to your computer and use it in GitHub Desktop.
lazy loading problem
struct Context {
foo: Option<String>,
bar: Option<String>
}
impl Context {
fn new() -> Self {
Context {
foo: None,
bar: None
}
}
fn foo(&mut self) -> &str {
if self.foo.is_none() {
let message = String::from("foo");
self.foo = Some(message);
}
self.foo.as_ref().unwrap()
}
fn bar(&mut self) -> &str {
if self.bar.is_none() {
let message = String::from("bar");
self.bar = Some(message);
}
self.bar.as_ref().unwrap()
}
}
fn print(context: &mut Context) {
let foo = context.foo();
let bar = context.bar();
println!("{}{}", foo, bar);
}
fn main() {
let mut context = Context::new();
print(&mut context);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment