title: How do I properly implement a caching struct in Rust for lazily-computed values?
body: <p>In Rust, I'm searching for a more concise and idiomatic way to define a cache for expensive calculations.</p>
  
  <p>In Chapter 13 from the Second Edition of <em>The Rust Programming Language</em>, the authors leave an exercise for the reader to refactor a struct to return lazily-computed values.</p>
  
  <p>After four days of trial and error, I came up with:</p>
  
  <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
  
  #[allow(dead_code)]
  struct Cache&lt;T&gt; 
      where T: Fn(u32) -&gt; u32
  {
      calculation: T,
      internal: HashMap&lt;u32, u32&gt;
  }
  
  #[allow(dead_code)]
  impl&lt;T&gt; Cache&lt;T&gt;
      where T: Fn(u32) -&gt; u32
  {
      fn new(calculation: T) -&gt; Cache&lt;T&gt; {
          Cache {
              calculation,
              internal: HashMap::new(),
          }
      }
  
      fn set(&amp;mut self, arg: u32, value: u32) -&gt; u32 {
          self.internal.insert(arg, value);
          self.get(arg)
      }
  
      fn get(&amp;mut self, arg: u32) -&gt; u32 {
          self.internal[&amp;arg]
      }
  
      fn value(&amp;mut self, arg: u32) -&gt; u32 {
          match self.internal.contains_key(&amp;arg) {
              true =&gt; {
                  self.get(arg)
              },
              false =&gt; {
                  self.set(arg, (self.calculation)(arg))
              },
          }
      }
  }
  </code></pre>
  
  <p>For the test function:</p>
  
  <pre class="lang-rust prettyprint-override"><code>#[test]
  fn call_with_different_values() {
      let mut c = Cache::new(|a| a);
      let _v1 = c.value(1);
      let v2 = c.value(2);
      assert_eq!(v2, 2);
  }
  </code></pre>
  
  <p>Can I improve this <code>impl</code>? Is there a more acceptable way for this to be written?</p>