Call methods from goroutine

I have an object A with some methods: Get1(), Get2(), Get3()…

That object is being used by a goroutine.

Another goroutine wants to call those Get methods.

How should this be done safely?

I can think of several ways of handling this.
A mutex could be added, but the guidance seems to be to use channels when possible.

My question is: what is the most idiomatic way of doing this safely in Go?

Thanks,
Mike

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.

Can you do something like this?

func main() {
	a := Obj.New()
	
	go func(b){
		b.Get1()
	
	}(&a)
	
	go func(c){
		c.Get2()
	
	}(&a)
	
	...
}

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.