Junior — Middle
What types of channels are used in the Go language for communication between goroutines?
sobes.tech AI
Answer from AI
In the Go language, channels (channels) are used for communication between goroutines and come in several types:
-
Buffered and unbuffered channels
- Unbuffered channel — blocks the sender until the receiver reads the value.
- Buffered channel — has an internal buffer of fixed size, allowing multiple values to be sent without blocking until the buffer is full.
-
Unidirectional channels
- Channels can be declared as send-only (
chan<- Type) or receive-only (<-chan Type), which helps restrict usage and improve code safety.
- Channels can be declared as send-only (
Example of creating and using a buffered channel:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1 // does not block
ch <- 2 // does not block
// ch <- 3 // blocks until someone reads
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
Thus, the main types of channels in Go are buffered/unbuffered and unidirectional/bidirectional.