title: Golang: Best way to evaluate a function once in a specific case
body: <p>Suppose, I have a <code>Eval</code> struct and multiple goroutines can call its <code>Evaluate</code> method to get the value of the <code>result</code> field. Following is the basic structure of code:</p>
  <pre><code>type Eval struct {
      done  bool
      result interface{}
  }
  
  func (e *Eval) Evaluate(f func() interface{}) interface{} {
      if e.done == false {
          e.result = f()
          e.done = true
      }
      return e.result
  }
  </code></pre>
  <p>As the function passed as argument of <code>Evaluate</code> method can take quite some time to execute, so I want to prevent calling that function multiple times. Only the first goroutine to call the <code>Evaluate</code> function will actually &quot;evaluate&quot; the value of result. The other goroutines will simply wait for the result field to be ready.</p>
  <p>Here is what I came up with:</p>
  <pre><code>type Eval struct {
      mu    *sync.Mutex
      cond  *sync.Cond // cond uses mu as sync.Locker
      once  *sync.Once
      done  bool
      result interface{}
  }
  
  func (e *Eval) Evaluate(f func() interface{}) interface{} {
      go e.once.Do(func() {
          defer e.cond.Broadcast()
  
          v := f()
          e.mu.Lock()
          e.result = v
          e.done = true
          e.mu.Unlock()
      })
  
      e.mu.Lock()
      if e.done == false {
          e.cond.Wait()
      }
      v := e.result
      e.mu.Unlock()
      return v
  }
  </code></pre>
  <p>But I feel like it is an overkill and using a <code>sync.Mutex</code> to control access to a variable that will be written once and read many times is not the efficient solution. What is the best and most &quot;golang&quot; way to achieve what I want?</p>
  <p>Edit: As mentioned in <a href="https://stackoverflow.com/questions/63590283/golang-best-way-to-evaluate-a-function-once-in-a-specific-case#comment112448154_63590283">comment</a>, only using <code>sync.Once</code> does the job.</p>