1. Create
No buffering
var chs1 = make (chan int)
var chs2 = make (chan float64)
var CHS3 = make (Chan string)
With buffering
var chs1 = make (chan int, 3)
var chs2 = make (chan float64, 3)
var CHS3 = Make (Chan string, 3)
There is the difference between buffering and no buffering:
Buffering mode when writing data and can write directly when the buffer is not full, will not block, the buffer is full, will block waiting for the other party to read,
Non-buffered mode writes are blocked until the other person reads the data
Read Data buffer mode can read buffer existing data, otherwise need to block waiting for each other to write
unbuffered mode requires blocking wait for each other to write
2. Close
var chs1 = make (chan int)
Close (CHS1)
After a closed channel read, the Chan int type returns 0,chan BOOL returns False,chan string returns null
It is also possible to judge:
V, OK: = <-chs1//chs1 OK is false after closing
If OK {
Fmt. Println (v)
}
After the closed channel is written panic
3. Timeout
The channel itself has not timed out
In general, do this:
CH: = make (chan int)
T: = time. After (time. Second * 2)
Select {
Case V, OK: = <-ch:
If OK {
Do something
}
Case <-T:
Fmt. PRINTLN ("timeout")
}
Go Channel Summary