這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
類型(續)
指標類型
指標類型表示所有給定類型的指標變數,也稱為基礎類型的指標,預設未初始化的指標類型值為nil。
PointerType = "*" BaseType .BaseType = Type .*Point*[4]int
函數類型
函數類型表示擁有相同參數和傳回值類型的函數,未初始化的函數類型變數的值為nil,定義如下
FunctionType = "func" Signature .Signature = Parameters [ Result ] .Result = Parameters | Type .Parameters = "(" [ ParameterList [ "," ] ] ")" .ParameterList = ParameterDecl { "," ParameterDecl } .ParameterDecl = [ IdentifierList ] [ "..." ] Type .
參數或傳回值可以有零個或多個。還可以通過... 來指定變參類型,表示可傳遞0個或n個參數。
func()func(x int) intfunc(a, _ int, z float32) boolfunc(a, b int, z float32) (bool)func(prefix string, values ...int)func(a, b int, z float64, opt ...interface{}) (success bool)func(int, int, float64) (float64, *[]int)func(n int) func(p *T)
介面類型
介面類型表示一組方法的組合。介面類型的變數可以儲存引用任意類型T,只要T的方法都實現該介面的方法,這樣的T類型可以被稱為實現了該介面,未初始化的介面類型變數值為nil
InterfaceType = "interface" "{" { MethodSpec ";" } "}" MethodSpec = MethodName Signature | InterfaceTypeName MethodName = identifierInterfaceTypeName = TypeName
介面的所有方法必須是唯一的非空白名稱
// A simple File interfaceinterface { Read(b Buffer) bool Write(b Buffer) bool Close()}
任意的一個或多個類型都可實現此介面,例如T類型
func (p T) Read(b Buffer) bool { return … }func (p T) Write(b Buffer) bool { return … }func (p T) Close() { … }
空類型不包含任何方法,因此所有的類型都實現了空介面
interface{}
介面可以嵌套
介面T可以使用介面E作為嵌入欄位,則T隱式的包含E的所有方法
type Locker interface { Lock() Unlock()}type File interface { ReadWriter // same as adding the methods of ReadWriter Locker // same as adding the methods of Locker Close()}
切記:介面不可迴圈嵌套
// illegal: Bad cannot embed itselftype Bad interface { Bad}
Map(K-V)類型
Map類型表示K類型到V類型的映射,未初始化的Map類型預設為nil
MapType = "map" "[" KeyType "]" ElementType .KeyType = Type .
在key類型上需要執行運算元的比較運算(== 和 !=),因此key類型不能是函數類型、map類型、slice類型。如若key是一個介面類型,則key必須要定義一個動態值才能執行比較運算,否則會造成一個運行時panic 異常。
map[string]intmap[*T]struct{ x, y float64 }map[string]interface{}
可使用內建的函數len 來計算map的大小,delete 來移除元素
建立map時,用make 函數,並可指定其容量
make(map[string]int)make(map[string]int, 100)
管道(Channel)類型
管道(Channel)類型通過發送和接收指定類型的值來實現通訊,並以此提供一種機制來實現並發執行的功能。未初始化的值也是nil.
ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType
<- 操作符指定了管道的發送和接收的方向,若沒有指定方向,則代表是雙向的,管道只能順序發送或接收。
chan T // can be used to send and receive values of type Tchan<- float64 // can only be used to send float64s<-chan int // can only be used to receive ints
使用make 方法來建立管道
make(chan int, 100)
最後一個參數表示容量,可以省略。定義了該參數,表示此管道是一個緩衝管道,因此該管道只能儲存指定的大小的元素,當超出長度後,則會阻塞,直到goroutine從管道中讀取一些元素,騰出空間。
可用close 函數來關閉管道。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。