title: What is the idiomatic way to implement caching on a function that is not a struct method?
body: <p>I have an expensive function like this:</p>
  
  <pre><code>pub fn get_expensive_value(n: u64): u64 {
     let ret = 0;
     for 0 .. n {
         // expensive stuff
     }
     ret
  }
  </code></pre>
  
  <p>And it gets called very frequently with the same argument. It's pure, so that means it will return the same result and can make use of a cache. </p>
  
  <p>If this was a struct method, I would add a member to the struct that acts as a cache, but it isn't. So my option seems to be to use a static:</p>
  
  <pre><code>static mut LAST_VAL: Option&lt;(u64, u64)&gt; = None;
  
  pub fn cached_expensive(n: u64) -&gt; u64 {
     unsafe {
         LAST_VAL = LAST_VAL.and_then(|(k, v)| {
             if k == n {
                Some((n,v))
             } else {
                None
             }
         }).or_else(|| {
             Some((n, get_expensive_value(n)))
         });
         let (_, v) = LAST_VAL.unwrap();
         v
     }
  }
  </code></pre>
  
  <p>Now, I've had to use <code>unsafe</code>. Instead of the <code>static mut</code>, I could put a <code>RefCell</code> in a <code>const</code>. But I'm not convinced that is any safer - it just avoids having to use the <code>unsafe</code> block. I thought about a <code>Mutex</code>, but I don't think that will get me thread safety either.</p>
  
  <p>Redesigning the code to use a struct for storage is not really an option.</p>