Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub struct Cache<F, V>
- where F: FnOnce() -> V
- {
- calculation_fn: Option<F>,
- value: Option<V>,
- }
- impl<F, V> Cache<F, V>
- where F: FnOnce() -> V
- {
- pub fn new(calculation: F) -> Cache<F, V> {
- Cache {
- calculation_fn: Some(calculation),
- value: None,
- }
- }
- pub fn value(&mut self) -> &V {
- match &self.value {
- None => {
- let calculation_fn = self.calculation_fn.take().unwrap();
- let calculation = (calculation_fn)();
- self.value = Some(calculation);
- ()
- },
- _ => (),
- };
- match &self.value {
- Some(ref v) => v,
- None => unsafe { hint::unreachable_unchecked() },
- }
- }
- }
- fn main() {
- let mut counter = 0;
- let mut sut = Cache::new(|| {
- counter += 1;
- 42
- });
- sut.value();
- sut.value();
- assert_eq!(42, *sut.value());
- assert_eq!(counter, 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement