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])
- Sending data to a channel: ch <- 10
- Receiving data from a channel: x := <-ch
- 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:
- If a goroutine attempts to send first, there must be another goroutine ready to receive on the channel; otherwise, the send operation will block;
- If a goroutine attempts to receive first, there must be another goroutine ready to send on the channel; otherwise, the receive operation will block;
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.
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