}
func AsyncService() chan string {
retCh := make(chan string, 1)//创建一个容量为1元素类型为string的通道
go func() {
ret := service()
fmt.Println(“returned result.”)
retCh <- ret//将值放入通道retCh中
fmt.Println(“service exited.”)
}()
return retCh
}
func TestAsynService(t *testing.T) {
retCh := AsyncService()
otherTask()
fmt.Println(<-retCh)//从通道retCh中取去出一个值
time.Sleep(time.Second * 1)
}
通道创建语法: make(chan 元素类型, 容量),容量是可选值指通道最多可以缓存多少元素值,这个值不能为负数
当容量为0时,称为非缓冲通道,大于0时称为缓冲通道
通道是个队列,遵循先进先出的原则
元素值的发送和接受都需要用接收操作符 <-
进入通道的并不是在接受操作符右边的那个元素,而是它的副本