Junior — Middle
How often do you use channels to organize data transfer between goroutines?
sobes.tech AI
Answer from AI
In Go, channels (channels) are the primary mechanism for safe data transfer between goroutines and synchronizing their operation. The frequency of channel usage depends on the application's architecture and tasks.
Channels are typically used:
- When data needs to be transferred between parallel tasks without using shared variables.
- To organize task queues.
- To synchronize the completion of goroutines.
An example of channel usage:
package main
import (
"fmt"
)
func worker(ch chan string) {
msg := <-ch
fmt.Println("Received message:", msg)
}
func main() {
ch := make(chan string)
go worker(ch)
ch <- "Hello from main"
}
Thus, channels are a standard and recommended way of communication between goroutines, and they should be used whenever data exchange or execution synchronization is needed.