本文主要給大家介紹的是關(guān)于golang單向channel語(yǔ)法的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話不多說(shuō),來(lái)一起看看詳細(xì)的介紹:
今天閑來(lái)無(wú)事補(bǔ)充一下golang的語(yǔ)法知識(shí),想起來(lái)看看context的用法,結(jié)果碰到了一個(gè)沒(méi)見(jiàn)過(guò)的channel語(yǔ)法:
// 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{}
,一個(gè)接口函數(shù)的聲明怎么這么奇怪呢?下面來(lái)分解一下。
Done() chan struct{}
:如果函數(shù)定義改成這樣,其意義是,
- 函數(shù)名Done,參數(shù)(),返回值
chan struct{}
。
- 單獨(dú)拿返回值來(lái)說(shuō),它是一個(gè)管道chan,內(nèi)部的數(shù)據(jù)類型是
struct{}
。
- 單獨(dú)拿struct{}來(lái)說(shuō),我們熟悉
type Name struct{a int, b bool}
這樣去定義一個(gè)結(jié)構(gòu)體的類型,其實(shí)struct{…}就是定義結(jié)構(gòu)體,和map[string]int這種定義是一樣的,type只是給它啟了一個(gè)別名。
- chan struct{}
:?jiǎn)为?dú)看這個(gè)表達(dá)式,我們知道如果ch := make(chan struct{})
,那么- ch是從管道里取出數(shù)據(jù)。但是chan struct{}
是類型而不是變量,竟然能從一個(gè)類型里取數(shù)據(jù)??
其實(shí)-chan int
仍舊是一個(gè)管道類型,它叫做單向channel。如果是-chan int
,說(shuō)明是只能讀不能寫(xiě)的管道(也不能關(guān)閉),如果是chan - int
,說(shuō)明是只能寫(xiě)不能讀的管道(可以關(guān)閉),僅此而已!
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者使用Go語(yǔ)言能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
您可能感興趣的文章:- 基于golang channel實(shí)現(xiàn)的輕量級(jí)異步任務(wù)分發(fā)器示例代碼
- golang中for循環(huán)遍歷channel時(shí)需要注意的問(wèn)題詳解
- golang實(shí)現(xiàn)基于channel的通用連接池詳解
- Golang優(yōu)雅關(guān)閉channel的方法示例
- golang判斷chan channel是否關(guān)閉的方法
- Golang中channel使用的一些小技巧
- Golang中channel的原理解讀(推薦)