# Golang channels
[[golang]] channels are the datastructure (with language support) used to do [[Message passing]] in the golang language.
[[ZK - 2g3 - 2022-10-09 - Golang channels are complex datastructures]]
I went through the code for channels here:
- [[CODE - golang's channel datastructure - chan.go]]
I really recommend to anybody writing [[golang]] to read through that file and understand it.
### Rules
- writing to an unbuffered channel will block a [[goroutine]] until another [[goroutine]] receives data from the channel (or there are queued goroutines already present in `recvq`, see [[CODE - golang's channel datastructure - chan.go|code]])
- writing to a buffered channel when the buffer is full will block
- writing to a closed channel will panic
- reading from an unbuffered channel will block
From [[PAPER - Understanding Real-World Concurrency Bugs in Go]]:
- channels can only be used after initializing
- sending/receiving data to/from a `nil` channel will block forever
- sending data to a closed channel panics
- closing a closed channel panics
### Non-blocking operations
You can do non-blocking operations on channels:
- [Go by Example: Non-Blocking Channel Operations](https://gobyexample.com/non-blocking-channel-operations)
```go
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
```
## Links
What seems like a pretty exhaustive article about golang channels.
- [Channels in Go -Go 101](https://go101.org/article/channel.html)
The source for the channel datastructure:
- [go/chan.go at master · golang/go · GitHub](https://github.com/golang/go/blob/master/src/runtime/chan.go)
Articles about implementation:
- [cat /dev/head: Golang: channels implementation](http://dmitryvorobev.blogspot.com/2016/08/golang-channels-implementation.html)
- [Go channels on steroids](https://docs.google.com/document/d/1yIAYmbvL3JxOKOjuCyon7JhW4cSv1wy5hC0ApeGMV9s/pub)
- [How Does Golang Channel Works. Understanding Inner workings of the… | by Jerry An | Level Up Coding](https://levelup.gitconnected.com/how-does-golang-channel-works-6d66acd54753)
- [Diving Deep Into The Golang Channels. | by Ankur Anand | codeburst](https://codeburst.io/diving-deep-into-the-golang-channels-549fd4ed21a8)
Talks:
- [GopherCon 2017: Kavya Joshi - Understanding Channels - YouTube](https://www.youtube.com/watch?v=KBZlN0izeiY)