Sobes.tech
Senior

What types of channels exist in Go and what is each used for?

sobes.tech AI

Answer from AI

In Go, channels come in two main types:

  1. Buffered channels — have an internal buffer of fixed size. The sender can write multiple values into the channel without blocking until the buffer is full. They are used for asynchronous data transfer and smoothing out load peaks.

  2. Unbuffered channels — have no buffer. The sender blocks until the receiver reads the value. They are used for synchronization and data transfer between goroutines at the moment of transmission.

Example of creating and using a buffered channel:

ch := make(chan int, 3) // buffer of 3 elements
ch <- 1
ch <- 2
ch <- 3 // does not block, as buffer is not full

fmt.Println(<-ch) // 1

For an unbuffered channel:

ch := make(chan int) // no buffer

// in a separate goroutine
go func() {
    ch <- 42 // blocks until someone reads
}()

val := <-ch // reading unblocks the sender
fmt.Println(val) // 42

Channels can also be unidirectional (only for sending or only for receiving), which helps explicitly specify intentions in the code.

What types of channels exist in Go and what is each… - sobes.tech