Go channel

Go channel is a reference type, similar to a conveyor belt or a queue, which follows the First In First Out (FIFO) rule to ensure the order of data sending and receiving.

var variableName chan DataType

Using make

make(chan DataType, [bufferSize])
  1. Sending data to a channel: ch <- 10
  2. Receiving data from a channel: x := <-ch
  3. Closing a channel: close(ch)

Unbuffered Channels

An unbuffered channel is also known as a synchronous channel. Communication through an unbuffered channel requires that there must be a receiver ready before a sender can send:

  1. If a goroutine attempts to send first, there must be another goroutine ready to receive on the channel; otherwise, the send operation will block;
  2. If a goroutine attempts to receive first, there must be another goroutine ready to send on the channel; otherwise, the receive operation will block;

Go Unbuffered Channels

Buffered Channels

A buffered channel is represented by a channel with a capacity greater than zero. The capacity of a channel indicates the number of elements that can be stored in the channel. It's like a locker with a limited number of compartments; once all compartments are full, no more items can be added until one is removed, allowing a new item to be placed. This results in blocking until space is available.

Go Buffered Channels

ch := make(chan int, 1)
ch <- 10
x := <-ch
fmt.Println("x:", x)
close(ch)

 

Take a break

👉👉👉 【BTTH Year EP108】Xiao Yan sent love message back to Medusa and prepared to rescue Xiao Yixian