Last active
June 18, 2017 14:35
-
-
Save greyblake/069eca5993e154cc01d27db6f7785fd3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
use std::cell::Cell; | |
#[derive(Debug)] | |
struct Ab { | |
a: i32, | |
b: i32, | |
cache: Cell<Option<i32>> | |
} | |
impl Ab { | |
fn new(a: i32, b: i32) -> Self { | |
Self { a, b, cache: Cell::new(None)} | |
} | |
fn a_plus_b(&self) -> i32 { | |
match self.cache.get() { | |
None => { | |
let sum = self.a + self.b; | |
println!("Calculating sum"); | |
self.cache.set(Some(sum)); | |
sum | |
}, | |
Some(val) => { | |
println!("Using cached value"); | |
val | |
} | |
} | |
} | |
} | |
fn main() { | |
let ab = Ab::new(4, 7); | |
println!("ab = {:?}", ab); | |
println!("ab.a_plus_b() = {:?}", ab.a_plus_b()); | |
println!("ab.a_plus_b() = {:?}", ab.a_plus_b()); | |
println!("ab = {:?}", ab); | |
} | |
// output: | |
// ab = ab { a: 4, b: 7, cache: cell { value: none } } | |
// Calculating sum | |
// ab.a_plus_b() = 11 | |
// using cached value | |
// ab.a_plus_b() = 11 | |
// ab = ab { a: 4, b: 7, cache: cell { value: some(11) } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment