Go Channel
- Posted on
- Authors
- Name
- ansidev
- @ansidev
My notes about Go channel.
Channels are a typed conduit through which you can send and receive values with the channel operator,
<-
.
Channel can only save homogeneous data type. So you must declare the type of the channel you want to create.
chan int // channel only accepts int chan string // channel only accepts string chan bool // channel only accepts bool
chan int // channel only accepts int chan string // channel only accepts string chan bool // channel only accepts bool
You need to initialize a channel before using it with
make
, otherwise the channel isnil
and not available to use.// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // works var ch2 chan int // don't work
// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // works var ch2 chan int // don't work
You need to initialize a channel before using it with
make
.ch := make(chan int) // int is type of channel data
ch := make(chan int) // int is type of channel data
Sending/Receiving data using channel:
x := <- ch // read data from channel ch into variable x ch <- y // send y to the channel ch
x := <- ch // read data from channel ch into variable x ch <- y // send y to the channel ch
Close a channel:
close(ch)
close(ch)
Note: You cannot send data to a closed channel.
Type of channels:
unbuffered channel
: a channel is created with no capacity.// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // unbuffered channel
// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // unbuffered channel
buffered channel
: a channel is created with capacity.// Syntax: {variable_name} := make(chan {type}, {capacity}) ch := make(chan int, 5) // buffered channel, capacity = 5
// Syntax: {variable_name} := make(chan {type}, {capacity}) ch := make(chan int, 5) // buffered channel, capacity = 5
Channel blocking mechanism:
Unbuffered channel
Sending and receiving are blocked until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
ch := make(chan int) // unbuffered channel
ch := make(chan int) // unbuffered channel
Buffered channel
Sending data to a buffered channel are blocked only when the buffer is full.
Receiving data from a buffered channel are blocked only when the buffer is empty.
ch := make(chan int, 5) // buffered channel
ch := make(chan int, 5) // buffered channel
Deadlock with channel
A deadlock happens when a group of goroutines are waiting for each other and none of them is able to proceed. Examples:
- The data which are sent into a channel cannot be received by any receiver anywhere in your code.
- You try to read data from a channel but there is no data are sent to the channel anywhere in your code.