1. 程式人生 > >17-golang中單向channel的應用

17-golang中單向channel的應用

 

將channel傳入方法

但是可以轉換為單向的channel

channelSend chan<- int

channelReceive <-chan int

 

 

func main() {

   channel := make(chan int)

   go producer(channel)

   consumer(channel)
}

func producer(send chan<- int) {
   for i := 0; i < 10; i++ {
      send <- i
   }
   close(send)
}

func consumer(receive <-chan int) {
   for num := range receive {
      fmt.Println("receive", num)
   }
}