Skip to content

Instantly share code, notes, and snippets.

@Cijin
Last active April 21, 2022 10:04
Show Gist options
  • Save Cijin/b281dc1093759720a0b2e596d4a41609 to your computer and use it in GitHub Desktop.
Save Cijin/b281dc1093759720a0b2e596d4a41609 to your computer and use it in GitHub Desktop.
Buffered channels and how they differ from Unbuffered channels

Buffered Channels

A buffered channel is a channel that can hold one or more values before they are recieved. There are also different conditions when send and recieve will block:

  • Recieve will block if there is no value in the channel
  • Send will block if there is no space in the buffer for the incoming value

Creating an unbuffered channel

var bufferedChan = make(chan int, capacity) // where capacity is the number of ints the channel can hold

Closing Channel

Closing the channel is important. When a channel is closed you can still recieve from the channel but no longer send. If you request the optional flag on channel recieve you can get the state of the channel

close(bufferedChan)

v, ok := <-bufferedChan

if !ok {
  // this means the channel is empty and closed
}

Finally

Unbuffered channels provide a guarantee b/w an exchange of data, Buffered channels don't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment