golang單向channel文法

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

今天閑來無事補充一下golang的文法知識,想起來看看context的用法,結果碰到了一個沒見過的channel文法:

Go
123456789101112131415161718 // A Context carries a deadline, cancelation signal, and request-scoped values// across API boundaries. Its methods are safe for simultaneous use by multiple// goroutines.type Context interface {    // Done returns a channel that is closed when this `Context` is canceled    // or times out.    Done() <-chan struct{}     // Err indicates why this Context was canceled, after the Done channel    // is closed.    Err() error     // Deadline returns the time when this Context will be canceled, if any.    Deadline() (deadline time.Time, ok bool)     // Value returns the value associated with key or nil if none.    Value(key interface{}) interface{}}

注意看Done() <- chan struct{},一個介面函數的聲明怎麼這麼奇怪呢?下面來分解一下。

  • Done() chan struct{}:如果函數定義改成這樣,其意義是,
    • 函數名Done,參數(),傳回值chan struct{}。
    • 單獨拿傳回值來說,它是一個管道chan,內部的資料類型是struct{}。
    • 單獨拿struct{}來說,我們熟悉type Name struct{a int, b bool}這樣去定義一個結構體的類型,其實struct{…}就是定義結構體,和map[string]int這種定義是一樣的,type只是給它啟了一個別名。
  • <- chan struct{}:單獨看這個運算式,我們知道如果ch := make(chan struct{}),那麼<- ch是從管道裡取出資料。但是chan struct{}是類型而不是變數,竟然能從一個類型裡取資料??

其實<-chan int仍舊是一個管道類型,它叫做單向channel。如果是<-chan int,說明是只能讀不能寫的管道(也不能關閉),如果是chan <- int,說明是只能寫不能讀的管道(可以關閉),僅此而已!(擴充閱讀)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.