Senior
How is a channel in Go organized under the hood, what types are there, and what are the features?
sobes.tech AI
Answer from AI
In Go, a channel is a primitive for communication between goroutines, implementing the CSP (Communicating Sequential Processes) pattern. Under the hood, a channel is a blocking queue that ensures safe data exchange between goroutines.
Channel types:
- Buffered — have an internal buffer of fixed size, allowing multiple messages to be sent without blocking.
- Unbuffered — block the sender until the receiver reads the message.
Features:
- Channels provide synchronization and data transfer simultaneously.
- You can close a channel to signal the end of transmission.
- Channels are typed, ensuring type safety.
Example of a buffered channel:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1
ch <- 2
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
Thus, channels in Go are a powerful tool for organizing safe and convenient data exchange between concurrent execution flows.