Junior — Middle
How does interaction between goroutines occur in Go?
sobes.tech AI
Answer from AI
In the Go language, interaction between goroutines primarily occurs through channels. Channels allow safe data transfer between goroutines, providing synchronization and message exchange.
Main points:
- A channel is created using
make(chan Type). - Sending data to a channel blocks the sender if the channel is full (for buffered channels) or if there is no receiver.
- Receiving from a channel blocks the receiver if the channel is empty.
Example of interaction:
dataCh := make(chan int)
go func() {
dataCh <- 42 // sending value to the channel
}()
value := <-dataCh // receiving value from the channel
fmt.Println(value) // 42
Thus, channels enable goroutines to exchange data and synchronize without using explicit locks.