Created
November 2, 2021 16:09
-
-
Save gammazero/eaa8faa67dabacfdc8d2c732bbf84cc5 to your computer and use it in GitHub Desktop.
Golang channel notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Channel Behaviors | |
* 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 | |
* 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 | |
* A for .. range reads until channel closes | |
* Calling close() on a nil channel panics | |
// F returns read-only channel of int. | |
func F() <-chan int { ... } | |
// F returns a write-only channel of int. | |
func F() chan<- int { ... } | |
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