func TestCodeRes(t *testing.T) {
require := make(chan int, 5)
for i := 0; i < 5; i++ {
require <- i
}
//关闭 require
close(require)
//设置定时器控制读取速率
ti := time.Tick(time.Duration(1) * time.Second)
//直接range只会读取值,缓冲区无数据会读取默认零值,chan关闭,则退出range
for i := range require {
<-ti
fmt.Printf("i: %d time: %v\n", i, time.Now())
}
// === RUN TestCodeRes
// i: 0 time: 2022-10-23 20:06:52.6746003 +0800 CST m=+1.026004901
// i: 1 time: 2022-10-23 20:06:53.6702704 +0800 CST m=+2.021675001
// i: 2 time: 2022-10-23 20:06:54.6643626 +0800 CST m=+3.015767201
// i: 3 time: 2022-10-23 20:06:55.6645058 +0800 CST m=+4.015910401
// i: 4 time: 2022-10-23 20:06:56.6647772 +0800 CST m=+5.016181801
// --- PASS: TestCodeRes (5.01s)
// PASS
结论:close(),会在最后一个send的值被receive了以后执行,这里就是 for range 循环完以后执行。通过官方文档的介绍也是可以知道的
// The close built-in function closes a channel, which must be either
// bidirectional or send-only. It should be executed only by the sender,
// never the receiver, and has the effect of shutting down the channel after
// the last sent value is received. After the last value has been received
// from a closed channel c, any receive from c will succeed without
// blocking, returning the zero value for the channel element. The form
// x, ok := <-c
// will also set ok to false for a closed channel.
func close(c chan<- Type)
}
