Use of method calls vs channel


I’m getting more familiar with Go’s concurrency patterns and I want to clarify the best practices.

  1. I understand that we want to use channels for the communication
    between goroutines. That being said are there cases where struct
    methods calls make sense or channels are to be used in every
  2. When communicating messages / struct that are processed
    (not modules that are passed around / registered etc.) is it better to pass
    them by value so that we don’t risk to have two goroutines modifying
    it at the same time?


You cannot communicate with another goroutine using method calls, or function calls. When you call a function from a goroutine, that function executes in the goroutine that called it. You can only communicate with another goroutine using channels, or by sharing memory and using synchronization primitives in the sync package to prevent race conditions.

The second part of the question depends on the situation.



In the above scenario, g1 and g2 are separate goroutines. Say, g2 sends the value (not pointer) x to g1. Then g1 gets a copy of x, and both goroutines can work on their copy. If x is a pointer, then g1 gets a pointer to x, and then g1 and g2 have to coordinate access to the value pointer to by that pointer.

So, if g2 does not read or modify the value x after sending it to g1, then it is fine to send the pointer to avoid copy.

Answered By – Burak Serdar

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.