Sobes.tech
Junior — Middle

What methods are used for data transfer when interacting between goroutines in Go?

sobes.tech AI

Answer from AI

In Go, the following main methods are used for communication between goroutines (lightweight threads):

  1. Channels — the primary and recommended method. Channels allow safe transmission of values between goroutines, providing synchronization and data exchange.
ch := make(chan int)
go func() {
    ch <- 42 // send value to channel
}()
value := <-ch // receive value from channel
  1. Shared variables with synchronization — using shared data with mutexes (sync.Mutex) or other synchronization primitives to prevent race conditions.

  2. sync package — provides various tools for goroutine coordination, such as WaitGroup, Cond.

However, in Go, it is customary to avoid shared memory access and prefer data passing through channels, which simplifies development and enhances safety.