Junior — Middle
Kuidas sa oma projektis kanalitega töötad?
sobes.tech AI
Vastus AI-lt
In my project, working with channels in Go is based on their use for synchronization and data exchange between goroutines. I usually create channels with the required data type, such as chan int or chan string, and use them for transmitting messages or signals.
An example of simple channel usage:
func worker(ch chan int) {
for val := range ch {
fmt.Println("Received value:", val)
}
}
func main() {
ch := make(chan int)
go worker(ch)
ch <- 10
ch <- 20
close(ch) // Close the channel so the worker ends the loop
}
It is also important to properly close channels to avoid blocking, and to use select for working with multiple channels simultaneously. In projects, I often use buffered channels to prevent blocking under high load.