Skip to content

Instantly share code, notes, and snippets.

@gammazero
Created June 13, 2024 17:34
Show Gist options
  • Save gammazero/201c545b48d9cd4a771f3bb40cf68f18 to your computer and use it in GitHub Desktop.
Save gammazero/201c545b48d9cd4a771f3bb40cf68f18 to your computer and use it in GitHub Desktop.

Channel Behaviors

Reading a channel

  • A receive from a nil channel blocks forever
  • A receive from a closed channel returns the zero value immediately
  • A receive on an empty channel blocks

Writing a channel

  • A send to a nil channel blocks forever
  • A send to a closed channel panics
  • A send to a full (or unbuffered) channel blocks until reader has read data

Closing a channel

  • Calling close() on a nil channel panics
  • Calling close() on a closed channel panics

Ranging a channel

  • A for .. range reads until channel closes
  • A range loop is the prefered (and fastest) way to read a channel until closed.

Declaring channel directionality: read-only and write-only

  • Read-only: var readChan <-chan
  • Write-only: var writeChan chan<-
// F returns read-only channel of int.
func F() <-chan int { ... }

// F returns a write-only channel of int.
func F() chan<- int { ... }

Channel Size 0 or 1, unless specific size known

I believe there are only two values for a channel's buffer, 0 and 1. Setting a value higher than 1 is really saying "well, I sort of want to buffer as much as I can, I hope this number is enough", and that is not a stable way to design systems. -- Dave Cheney

Principles of designing Go APIs with channels

From https://inconshreveable.com/07-08-2014/principles-of-designing-go-apis-with-channels/

Principle #1

An API should declare the directionality of its channels.

Principle #2

An API that sends an unbounded stream of values into a channel must document how it behaves for slow consumers.

Principle #3

An API that sends a bounded set of values into a channel it accepted as an argument must document how it behaves for slow consumers.

Principle #4

An API that sends an unbounded stream of values into a channel should accept the channel as an argument instead of returning a new channel.

Principle #5

An API which sends a bounded number of values may do so safely by returning an appropriately buffered channel.

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