1. The value passed in the channel is a backup of the original value, and the value taken from the channel is also a backup of the value in the channel.
2. If you want to transfer the same value through the channel, you can pass the pointer to this value.
3. When closing the channel, it must be closed from the sending end. If it is closed from the receiving end, it will cause panic.
4. The sending end will not affect the receiving end
5. The difference between channel with buffer and without buffer is whether the length is 0, and channel without buffer is 0
6. The operation of the channel that has not been initialized will be permanently blocked
var demo chan int
//For will be permanently blocked
for i:=range demo{
}
7. How to receive data from channel
var demochan=make(chan int,10)
/*
if method
Before the channel is closed, if there is no value in the channel, it will be blocked in the if statement, and if there is, it will be removed.
If the channel is closed, ok is false and if is no longer blocked
*/
for{
if value,ok:=<-demochan;ok{
fmt.println(value)
}else{
break
}
}
/*
For loop method:
Before the channel is closed, if there is a value in the channel, it will be removed otherwise for blocking.
After the channel is closed, for will exit and no longer block.
*/
for for i:=range demochan{
fmt.Println(i)
}
/*
Select method
The condition of each case in select needs to be a condition for the chan operation
If no case can be triggered, default is executed. If multiple cases are triggered, a case will be executed randomly.
The following example will have different results every time you execute it
*/
chanCap:=5
intchan:=make(chan int,chanCap)
for i:=0;i<chanCap;i++{
select{
case intchan<-1:
case intchan<-2:
case intchan<-3:
}
}
for i:=0;i<chanCap;i++{
fmt.Println(<-intchan)
}
/*
for shared with select
Supplementary knowledge:
Loop can identify the position where the Loop is next to the code below. The Loop in the code is above the for. The last break Loop means break for loop instead of break select
*/
intChan:=make(chan int,10)
for i:=0;i<10;i++{
intChan<-i
}
close(intChan)
synChan:=make(chan struct{},1)
go func(){
Loop:
for{
select{
case e,ok:=<-intChan:
if !ok{
fmt.Println("End.")
break Loop
}
fmt.Printf("Received: %v\n",e)
}
}
synChan<- struct{}{}
}()
<-synChan