這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
型別宣告包括:常量、自訂類型、變數、函數、標籤、還有包聲明。
程式中的標識符都必須聲明。塊、包、檔案中的標識符不能重複。
Declaration = ConstDecl | TypeDecl | VarDecl .TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
標籤範圍
標籤是在標籤語句中使用,常用在break、continue、goto語句中。定義了標籤但不使用是非法的。與其他標識符相比,標籤是非塊範圍,不會與其他非標籤標識符有衝突。
預宣告身份識別符
如下的標識符在golang中已保留
Types: bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptrConstants: true false iotaZero value: nilFunctions: append cap close complex copy delete imag len make new panic print println real recover
可匯出方法或欄位
一個標識符可匯出讓另一個包訪問,只需要滿足
常量聲明
用const 關鍵字
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] IdentifierList = identifier { "," identifier } .ExpressionList = Expression { "," Expression } .
const Pi float64 = 3.14159265358979323846const zero = 0.0 // untyped floating-point constantconst ( size int64 = 1024 eof = -1 // untyped integer constant)const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constantsconst u, v float32 = 0, 3 // u = 0.0, v = 3.0
Itoa(枚舉)
itoa表示連續的無類型的整形常量,從0開始計算,當又有itoa出現時,又重新置為0.
const ( // iota is reset to 0 c0 = iota // c0 == 0 c1 = iota // c1 == 1 c2 = iota // c2 == 2)const ( a = 1 << iota // a == 1 (iota has been reset) b = 1 << iota // b == 2 c = 1 << iota // c == 4)const ( u = iota * 42 // u == 0 (untyped integer constant) v float64 = iota * 42 // v == 42.0 (float64 constant) w = iota * 42 // w == 84 (untyped integer constant))const x = iota // x == 0 (iota has been reset)const y = iota // y == 0 (iota has been reset)
型別宣告
用type
來定義一個新的類型
TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .TypeSpec = identifier Type .type IntArray [16]inttype ( Point struct{ x, y float64 } Polar Point)type TreeNode struct { left, right *TreeNode value *Comparable}type Block interface { BlockSize() int Encrypt(src, dst []byte) Decrypt(src, dst []byte)}
自訂類型不會繼承原有類型的方法,但介面方法或組合類別型的元素則保留原有的方法。
// A Mutex is a data type with two methods, Lock and Unlock.type Mutex struct { /* Mutex fields */ }func (m *Mutex) Lock() { /* Lock implementation */ }func (m *Mutex) Unlock() { /* Unlock implementation */ }// NewMutex has the same composition as Mutex but its method set is empty.type NewMutex Mutex// The method set of the base type of PtrMutex remains unchanged,// but the method set of PtrMutex is empty.type PtrMutex *Mutex// The method set of *PrintableMutex contains the methods// Lock and Unlock bound to its anonymous field Mutex.type PrintableMutex struct { Mutex}// MyBlock is an interface type that has the same method set as Block.type MyBlock Block
自訂類型可用於布爾、數值、或字串類型,還可為其附加方法
type TimeZone intconst ( EST TimeZone = -(5 + iota) CST MST PST)func (tz TimeZone) String() string { return fmt.Sprintf("GMT%+dh", tz)}
變數聲明
變數聲明表示建立一個或多個變數,然後為之綁定相互關聯類型,並賦之於初始值。
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .var i intvar U, V, W float64var k = 0var x, y float32 = -1, -2var ( i int u, v, s = 2.0, 3.0, "bar")var re, im = complexSqrt(-1)var _, found = entries[name] // map lookup; only interested in "found"
如果變數在聲明但未使用,編譯器會報錯
短變數聲明
短變數聲明文法
ShortVarDecl = IdentifierList ":=" ExpressionList .i, j := 0, 10f := func() int { return 7 }ch := make(chan int)r, w := os.Pipe(fd) // os.Pipe() returns two values_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
但,短變數聲明只能在函數內部,但在if、for、switch語句中可聲明為臨時變數。
函式宣告
文法如下
FunctionDecl = "func" FunctionName ( Function | Signature ) FunctionName = identifier Function = Signature FunctionBody FunctionBody = Block
方法聲明
方法是帶接受者的函數。文法如下
MethodDecl = "func" Receiver MethodName ( Function | Signature ) Receiver = Parameters
接收者可以示T或*T類型
func (p *Point) Length() float64 { return math.Sqrt(p.x * p.x + p.y * p.y)}func (p *Point) Scale(factor float64) { p.x *= factor p.y *= factor}