- Key features & usage idioms for a channel
- Type-safe
- Thread-safe (goroutine safe)
- FIFO queue
- Pass-by-address-value
- All things pass by value
- maps, slices, channels, functions are passed by "address" value (like a pointer)
- If you pass a
channel
to a function/method, caller & callee are referencing the samechannel
- Optionally buffered
- Only affects Senders (Not receivers)
- Go channels are designed for 1 writer, and multiple readers
range
will NOT stop recieving util channel is closed- Sender is responsible for closing channel
- If you have multiple senders, use a
sync.WaitGroup
to close when done
- If you have multiple senders, use a
- allocated with
make
// unbuffered channel of ints
c1 := make(chan int)
// unbuffered channel of empty struct (zero memory)
c2 := make(chan struct{})
// buffered channel of strings, capacity of 5
c3 := make(chan string, 5)
- sender blocks for first receiver
- receiver blocks for sender
- Buffer size == how many values to accept without a receiver
- runtime will
panic
if you send on a closed channel - Blocks when ...
- (unbounded) Unbuffered and receiver hasn't received
- (unbounded) writing to a full buffer (until there's buffer capacity)
- (briefly) writing to the non-full buffer (just long enough to commit the value)
- Send example:
responseCodeCh <- 200
- send on
nil
channel blocks forever - Sender side is responsible for closing the channel
- If you have multiple senders, use a
sync.WaitGroup
to close when done
- If you have multiple senders, use a
- Blocks when ...
- (unbounded) no messages available
- (unbounded) when buffer empty
- Reading from closed channel yields zero value immediately
- Only receiver can check if channel is closed
- Receive:
//TODO
- You can also use
select
+default
for non-blocking - receive on
nil
channel blocks forever - even if you read a channel using receive-assign syntax, it will block until there's a message or channel is closed
- TODO: range
TODO
- Example
func myReceiver(source <-chan bool) {
current := <-source
fmt.Println("I read this: %v", current)
}
TODO: more here
- Writing to closed channel causes
panic
- Example
func mySender(sink chan<- bool) {
sink <- true
}
TODO: more here
TODO TODO: https://www.golang-book.com/books/intro/10
- Use one-way channels as function args
- TODO: nil channel
- TODO: closed channel
- TODO: closing a channel
- TODO: channel with empty struct