Be cautious when calling methods that access shared state (like global variables or mutable data structures) from multiple goroutines. This can lead to race conditions, where the outcome depends on unpredictable scheduling of goroutines. Use synchronization mechanisms like mutexes or channels to ensure safe access to shared data.
Hello there, imho the idiomatic way will be to add mutex into the struct. I assume that since it’s get method, you just read data, without changing it. So it can be done something like this:
package main
type A struct {
sync.RWMutex
data string
}
func (a *A) Get() string {
a.RLock()
defer a.RUnlock()
return a.data
}
func main() {
a := &A{data: "some string"}
go func() {
fmt.Println(a.Get()) // Prints "some string"
}()
// Some code here, to let goroutine to finish...
}
Thanks for that!
Thought there might be something using channels.
I guess closures could be put on a channel to defer the calls to GetA.
But that adds a bunch of complexity.
Your example with a simple mutex seems like a better way to go.