Senior
How do channels work in Go and what are they used for?
sobes.tech AI
Answer from AI
Channels in Go are typed conduits for data transfer between goroutines, providing synchronization and message exchange.
Main features of channels:
- Allow safe data transfer between concurrent threads (goroutines) without using mutexes.
- A channel blocks the sender if the buffer is full and blocks the receiver if the buffer is empty.
- Support buffering, enabling sending multiple values without blocking.
Example of using a channel:
package main
import (
"fmt"
)
func worker(ch chan string) {
msg := <-ch // Receive message from channel
fmt.Println("Received message:", msg)
}
func main() {
ch := make(chan string) // Create an unbuffered channel
go worker(ch) // Launch goroutine
ch <- "Hello, channel!" // Send message
}
Channels are used for organizing communication and synchronization between goroutines, which simplifies writing concurrent code and reduces the likelihood of race condition errors.