title: What's the right way to have a thread-safe lazy-initialized possibly mutable value in Rust?
body: <p>I have a struct that contains a field that is rather expensive to initialize, so I want to be able to do so lazily. However, this may be necessary in a method that takes <code>&amp;self</code>. The field also needs to be able to modified once it is initialized, but this will only occur in methods that take <code>&amp;mut self</code>. </p>
  
  <p>What is the correct (as in idiomatic, as well as in thread-safe) way to do this in Rust? It seems to me that it would be trivial with either of the two constraints:</p>
  
  <ul>
  <li>If it only needed to be lazily initialized, and not mutated, I could simply use <a href="https://github.com/khuey/lazy-init" rel="nofollow noreferrer"><code>lazy-init</code></a>'s <code>Lazy&lt;T&gt;</code> type.</li>
  <li>If it only needed to be mutable and not lazy, then I could just use a normal field (obviously).</li>
  </ul>
  
  <p>However, I'm not quite sure what to do with both in place. <a href="https://doc.rust-lang.org/std/sync/struct.RwLock.html" rel="nofollow noreferrer"><code>RwLock</code></a> seems relevant, but it appears that there is considerable trickiness to thread-safe lazy initialization given what I've seen of <code>lazy-init</code>'s source, so I am hesitant to roll my own solution based on it.</p>