The example here implies that sync.Once.Do guarantees visibility across goroutines for the string var a. Is that also true if for example the function f() called by sync.Once.Do initializes multiple fields of a struct instance? Will all the fields of the struct instance be visible to other goroutines without any additional synchronization?
Let's break down the example:
The variable a
is set before the function setup()
returns because reads and writes within a single goroutine must behave as if they executed in the order specified by the program [1].
The single call to setup()
from once.Do()
happens before any call of once.Do()
returns [2].
Therefore, the variable a
is set before any call to once.Do()
returns. No further synchronization is required to establish this before relationship.
The question asks about struct fields, not a single variable as in the example. As far as the memory model is concerned, struct fields are variables. All of the logic that applies to the variable in the example applies to fields in a struct.