Junior — Middle
Can you explain how channels work in the system?
sobes.tech AI
Answer from AI
In Go, channels are a mechanism for passing data between goroutines, providing synchronization and message exchange.
A channel is created using make(chan Type) and can be buffered or unbuffered.
Main features:
- Sending to a channel blocks the sender if the channel is full (for buffered channels) or if there is no receiver (for unbuffered channels).
- Receiving from a channel blocks the receiver if the channel is empty.
- This allows safe data exchange between goroutines without using mutexes.
Example:
ch := make(chan int)
// Sending
go func() {
ch <- 42
}()
// Receiving
value := <-ch
fmt.Println(value) // Will print 42
Thus, channels simplify the organization of concurrent interactions in Go.