Buffered Channels

Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:

  1. ch := make(chan int, 100)

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

Modify the example to overfill the buffer and see what happens.

buffered-channels.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. ch := make(chan int, 2)
  5. ch <- 1
  6. ch <- 2
  7. fmt.Println(<-ch)
  8. fmt.Println(<-ch)
  9. }