Junior — Middle
How is information exchanged between goroutines in Go?
sobes.tech AI
Answer from AI
In Go, communication between goroutines is primarily done through channels. Channels allow safe data transfer between goroutines, providing synchronization and preventing race conditions.
Example of using a channel:
ch := make(chan int)
// Sending data in a goroutine
go func() {
ch <- 42
}()
// Receiving data in the main goroutine
value := <-ch
fmt.Println(value) // Will print 42
Channels can be buffered or unbuffered, which affects blocking behavior during send and receive operations. Additionally, other mechanisms like shared variables with mutexes can be used for communication, but channels are the idiomatic primary method in Go.