up:: [[Golang MOC]]
tags:: #note/develop #on/computing/programming/languages/golang
# Channels in Go
Channels can be thought of as pipes that [[Goroutines]] use to communicate.[^1]
Each channel has a type associated with it. This is the type of data that the channel is allowed to transport.
> [!info]
> The zero value of a channel is `nil`. Because of this, channels have to be defined using `make`.
## Declaring Channels
A channel can be declared as follows:
```go
// A channel of type `int`
var ch chan int
```
And it can be defined:
```go
ch = make(chan int)
```
## Sending and Receiving Data
```go
data := <- ch // read from channel ch
ch <- data // write to channel ch
```
Reading and writing a channel is blocking.
## Unidirectional Channels
It is possible to create channels that only send or only receive data:
```go
ch := make(chan<- int) // send-only channel
```
It is possible to convert a bidirectional channel to a send-only or receive-only channel (but not vice versa). This is useful for making a channel send-only or receive-only while inside a function, preventing the function from performing the wrong operation on a channel.
## Closing Channels
Senders can close channels to notify receivers that no more data will be sent:
```go
ch := make(chan int)
close(ch)
```
Receivers can use an additional variable while receiving data from a channel to check whether the channel has been closed:[^1]
```go
v, ok := <- ch
```
If `ok` is `false`, then the channel is closed.
## Buffered Channels
- Sends to a buffered channel is only blocked when the buffer is full[^2]
- Receives from a buffered channel is only blocked when the buffer is empty
# Footnotes
[^1]: golangbot. “Channels,” October 15, 2021. [https://golangbot.com/channels/](https://golangbot.com/channels/).
[^2]: golangbot. “Buffered Channels and Worker Pools,” October 15, 2021. [https://golangbot.com/buffered-channels-worker-pools/](https://golangbot.com/buffered-channels-worker-pools/).