1. 程式人生 > >GO語言學習:單通道

GO語言學習:單通道

1.單通道的應用價值

  約束其他程式碼行為,約束其他程式碼行為,約束其他程式碼行為

 

  1.函式的引數為單通道

  先看如下程式碼:

    func sendInt(ch chan <- int){

      ch<-rand.Intn(1000)

    }

  使用func關鍵字聲明瞭一個sendInt的函式,這個函式只接受一個chan<-int型別的引數,在這個函式中我們只能向引數ch傳送資料(通道為引用型別),而不能從他那裡去取資料,這樣就約束了程式碼的行為.

 

    type Notifier interface{

      sendInt(ch chan<-int)

    }

  Notifier介面中的方法sendInt只會接收一個傳送通道作為引數,所以在該介面所有實現型別的sendInt方法都會受到限制,當然你也可以傳一個通道進去,不過go會自動轉為傳送通道.

    intChan1:=make(chan int,2)

    sedInt(intChan1)

 

  2.函式宣告的結果列表中使用單通道

    func getIntChan() <-chan int{

      num:=5

      ch:=make(chan int,num)

      for i:=0;i<num;i++{

        ch<-i

      }

      close(ch)

      return ch

    }

  getIntChan函式返回的是一個接收通道型別的通道,這意味著我們只能在此通道中接收資料.

    intChan2:=getIntChan()

    for elem:=rang intChan2{

      fmt.Printf("The element in intChan2 %v\n",elem)

    }

  把函式的返回值賦給intChan2,然後用for語句迴圈去取資料,並打印出來.當intChan2中沒有資料時就會被阻塞在那一行.如果為nil,則永遠被阻塞在那一行.

2.select的用法

  在go中,select與c++的switch相似,但用法略有不同

    intChan:=make(chan int,1)

    select{

    case <-intChan:

    //todo

    default:

    //todo

    }  

    case只會執行一次,default為預設執行操作.每執行一個case會自動跳出,也可以自己使用break跳出select.

    在go中,select只和通道有關.