Middle+
What are channels in Go and what types are there?
sobes.tech AI
Answer from AI
Channels in Go are mechanisms for passing data between goroutines, providing synchronization and message exchange. They allow safe sharing of values without explicit locks.
Main types of channels:
- Buffered channels: have an internal buffer of fixed size. The sender can write to the channel until the buffer is full without blocking.
- Unbuffered channels: have no buffer, and sending blocks until the receiver reads the value, ensuring synchronization.
- Directional channels: channels limited to only sending (
chan<-) or only receiving (<-chan), which helps control the direction of data transfer.
Example of using a buffered channel:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1
ch <- 2
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
Channels are a key element of Go's concurrency model, enabling the construction of safe and efficient parallel programs.