Junior — Middle
How is interaction between goroutines carried out using channels in Go?
sobes.tech AI
Answer from AI
In Go, interaction between goroutines is carried out through channels, which allow safe data transfer between concurrent execution threads.
A channel is a typed queue into which one goroutine can send data, and another can receive it. This ensures synchronization and data exchange without using explicit locks.
Example:
ch := make(chan int) // create a channel for transmitting int
go func() {
ch <- 42 // send value into the channel
}()
value := <-ch // receive value from the channel
fmt.Println(value) // will output 42
Thus, channels enable goroutines to exchange messages and synchronize their work, avoiding data races.