起源
初学channel不久按照文档例子写的时候出现问题 receive from send-only type chan<- int
channel(只读,只写,可读写)
- 定义只读的channel
read_only := make (<-chan int)
- 定义只写的channel
write_only := make (chan<- int)
- 可同时读写
read_write := make (chan int)
参考代码
func Producer(p chan<- int) {
for i := 0; i < 10; i++ {
p <- i * 10
}
}
//修改 out chan<- int 为 out <-chan int
func Consumer(out chan<- int) {
for v := range out {
fmt.Println(v)
}
}
func TestProducer(t *testing.T) {
p := make(chan int, 20)
go Producer(p)
go Consumer(p)
}