官方參考
https://golang.org/ref/spec#Types
其中類型有:
Method sets 方法集合
Boolean types 布爾類型
Numeric types 數(shù)字類型
String types 字符串類型
Array types 數(shù)組類型
Slice types 切片類型
Struct types 結(jié)構(gòu)體類型
Pointer types 指針類型
Function types 函數(shù)類型
Interface types 接口類型
Map types 字典類型
Channel types 通道類型
Method sets 方法集合
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T
consists of all methods declared with receiver type T
. The method set of the corresponding pointer type *T
is the set of all methods declared with receiver *T
or T
(that is, it also contains the method set of T
). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blankmethod name.
The method set of a type determines the interfaces that the type implements and the methods that can be calledusing a receiver of that type.
接口類型Interface types的接口就是方法集合。若一組方法的接受參數(shù)都為參數(shù)T,把這組方法叫T類型的方法集合。T指針的對(duì)應(yīng)方法集合,其接受參數(shù)為T或者*T。這意味著T指針的方法集合包含T類型的方法集合。對(duì)結(jié)構(gòu)體來(lái)說(shuō),該規(guī)則同樣適用。任何類型都有一個(gè)空的方法集合。在方法集合中,每個(gè)方法都有一個(gè)非空的方法名稱。
類型的方法集合確定了該類型實(shí)現(xiàn)的接口,以及可以可以被該類型的接收器調(diào)用的方法。
Boolean types 布爾類型
A boolean type represents the set of Boolean truth values denoted by the predeclared constants true
and false
. The predeclared boolean type is bool
; it is a defined type.
布爾類型定義了布爾變量,可被賦值為常量true和false。該類型是已定義類型。例如可以使用char類型來(lái)定義。
Numeric types 數(shù)字類型
A numeric type represents sets of integer or floating-point values. The predeclared architecture-independent numeric types are:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
The value of an n-bit integer is n bits wide and represented using two's complement arithmetic.
uint either 32 or 64 bits
int same size as uint
uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
There is also a set of predeclared numeric types with implementation-specific sizes:
To avoid portability issues all numeric types are defined types and thus distinct except byte
, which is an alias for uint8
, and rune
, which is an alias for int32
. Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32
and int
are not the same type even though they may have the same size on a particular architecture.
數(shù)字類型包括整型和浮點(diǎn)。內(nèi)置聲明包括uint8 uint16 uint32 uint64以及int8 int16 int32 int64 float32 float64 complex64 complex128 byte rune。
N位整數(shù)是N位寬度,使用二進(jìn)制補(bǔ)碼計(jì)算。
與平臺(tái)無(wú)關(guān)的聲明包塊uint int uintptr。
除了byte和rune外,其他數(shù)字類型為已定義類型,而byte是uint8的別名,rune是int32的別名。在數(shù)字類型之間的轉(zhuǎn)換需要進(jìn)行顯示轉(zhuǎn)換。
String types 字符串類型
A string type represents the set of string values. A string value is a (possibly empty) sequence of bytes. Strings are immutable: once created, it is impossible to change the contents of a string. The predeclared string type is string
; it is a defined type.
The length of a string s
(its size in bytes) can be discovered using the built-in function len
. The length is a compile-time constant if the string is a constant. A string's bytes can be accessed by integer indices 0 through len(s)-1
. It is illegal to take the address of such an element; if s[i]
is the i
'th byte of a string, &s[i]
is invalid.
字符串類型可以表示所有字符串的值。一個(gè)字符串的值是一系列空或不空的字節(jié)序列。他的值不能被修改。字符串被創(chuàng)建后就不能修改內(nèi)容。我們使用string來(lái)聲明一個(gè)string類型。string類型是已定義類型。
一個(gè)字符串的長(zhǎng)度(其包含多少個(gè)字節(jié))可以使用內(nèi)建函數(shù)len來(lái)計(jì)算。在編譯器可以計(jì)算一個(gè)常量string的長(zhǎng)度。string類型的變量可以訪問(wèn)其位置0到位置len-1的值。對(duì)這些位置的元素,獲取其地址是非法的。使用s[i]表示s字符串第i個(gè)位置的元素,而&s[i]是非法的。
Array types 數(shù)組類型
An array is a numbered sequence of elements of a single type, called the element type. The number of elements is called the length and is never negative.
ArrayType = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = Type .
The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int
. The length of array a
can be discovered using the built-in function len
. The elements can be addressed by integer indices 0 through len(a)-1
. Array types are always one-dimensional but may be composed to form multi-dimensional types.
[32]byte
[2*N] struct { x, y int32 }
[1000]*float64
[3][5]int
[2][2][2]float64 // same as [2]([2]([2]float64))
數(shù)組類型是多個(gè)同類型的元素構(gòu)成的可數(shù)序列。元素的數(shù)量是數(shù)組的長(zhǎng)度。長(zhǎng)度不能為負(fù)數(shù)。
數(shù)組的長(zhǎng)度也是數(shù)組的一部分。他的值非負(fù),可以用int表示。數(shù)組的長(zhǎng)度使用len求出。數(shù)組的所有元素可以從位置0到len-1進(jìn)行訪問(wèn)。數(shù)組類型永遠(yuǎn)是一維的,進(jìn)行組合可以表示多位類型。
Slice types 切片
A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The value of an uninitialized slice is nil
.
SliceType = "[" "]" ElementType .
Like arrays, slices are indexable and have a length. The length of a slice s
can be discovered by the built-in function len
; unlike with arrays it may change during execution. The elements can be addressed by integer indices 0 through len(s)-1
. The slice index of a given element may be less than the index of the same element in the underlying array.
A slice, once initialized, is always associated with an underlying array that holds its elements. A slice therefore shares storage with its array and with other slices of the same array; by contrast, distinct arrays always represent distinct storage.
The array underlying a slice may extend past the end of the slice. The capacity is a measure of that extent: it is the sum of the length of the slice and the length of the array beyond the slice; a slice of length up to that capacity can be created by slicing a new one from the original slice. The capacity of a slice a
can be discovered using the built-in function cap(a)
.
A new, initialized slice value for a given element type T
is made using the built-in function make
, which takes a slice type and parameters specifying the length and optionally the capacity. A slice created with make
always allocates a new, hidden array to which the returned slice value refers. That is, executing
make([]T, length, capacity)
produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:
make([]int, 50, 100)
new([100]int)[0:50]
Like arrays, slices are always one-dimensional but may be composed to construct higher-dimensional objects. With arrays of arrays, the inner arrays are, by construction, always the same length; however with slices of slices (or arrays of slices), the inner lengths may vary dynamically. Moreover, the inner slices must be initialized individually.
切片表示底層數(shù)組的連續(xù)段,提供對(duì)該段位置的元素訪問(wèn)。切片的類型表示其元素的類型。未初始化的切片的值為nil。
與數(shù)組相同,切片的長(zhǎng)度可以使用len來(lái)求出。長(zhǎng)度通常小于原來(lái)的數(shù)組。
切片自初始化之后與低層數(shù)組共享存儲(chǔ)空間,多個(gè)切片可以共享同一個(gè)存儲(chǔ)空間。數(shù)組通常代表了不同的存儲(chǔ)空間。
切片的低層數(shù)組長(zhǎng)度可以超過(guò)切片的末端,使用cap可以計(jì)算切片的容量,容量是數(shù)組超出切片的值加上切片本身的值??梢酝ㄟ^(guò)對(duì)切片重新切分得到新的超過(guò)原長(zhǎng)度的切片。
使用內(nèi)建函數(shù)make創(chuàng)建指定類型的切片。make接受切片類型和切片的長(zhǎng)度,容量作為可選參數(shù)。使用make創(chuàng)建出來(lái)的切片總是被分配一個(gè)切片所引用的隱藏?cái)?shù)組,這意味著通過(guò)make創(chuàng)建長(zhǎng)度50容量100的切片make([]int, 50, 100)與通過(guò)new創(chuàng)建一個(gè)長(zhǎng)度100的數(shù)組并對(duì)其切片50的長(zhǎng)度new([100]int)[0:50]兩者的結(jié)果相同。
與數(shù)組相同,切片的長(zhǎng)度是一維的,但是可以表示更高的維度。對(duì)于數(shù)組來(lái)說(shuō),內(nèi)部的數(shù)組由于構(gòu)造的長(zhǎng)度相同,是不能改變的。復(fù)合切片的內(nèi)部長(zhǎng)度會(huì)變成動(dòng)態(tài)的,復(fù)合切片的內(nèi)部也需要單獨(dú)初始化。
Struct types 結(jié)構(gòu)體
A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (EmbeddedField). Within a struct, non-blank field names must be unique.
StructType = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .
EmbeddedField = [ "*" ] TypeName .
Tag = string_lit .
// An empty struct.
struct {}
// A struct with 6 fields.
struct {
x, y int
u float32
_ float32 // padding
A *[]int
F func()
}
A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.
// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
struct {
T1 // field name is T1
*T2 // field name is T2
P.T3 // field name is T3
*P.T4 // field name is T4
x, y int // field names are x and y
}
The following declaration is illegal because field names must be unique in a struct type:
struct {
T // conflicts with embedded field *T and *P.T
*T // conflicts with embedded field T and *P.T
*P.T // conflicts with embedded field T and *T
}
A field or method f
of an embedded field in a struct x
is called promoted if x.f
is a legal selector that denotes that field or method f
.
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
Given a struct type S
and a defined type T
, promoted methods are included in the method set of the struct as follows:
- If
S
contains an embedded fieldT
, the method sets ofS
and*S
both include promoted methods with receiverT
. The method set of*S
also includes promoted methods with receiver*T
. - If
S
contains an embedded field*T
, the method sets ofS
and*S
both include promoted methods with receiverT
or*T
.
A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.
struct {
x, y float64 "" // an empty tag string is like an absent tag
name string "any string is permitted as a tag"
_ [4]byte "ceci n'est pas un champ de structure"
}
// A struct corresponding to a TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers;
// they follow the convention outlined by the reflect package.
struct {
microsec uint64 `protobuf:"1"`
serverIP6 uint64 `protobuf:"2"`
}
結(jié)構(gòu)體是一系列字段的集合,每個(gè)字段有自己的名稱和類型。類型可以隱式指定。在結(jié)構(gòu)中非空字段名稱必須是唯一的。
結(jié)構(gòu)體可以為空。也可以包含int float等類型。如果使用_表示padding占位。
如果結(jié)構(gòu)體的字段只有類型而沒(méi)有名字,我們表示這個(gè)字段是嵌入字段。嵌入字段的類型必須是類型T,或者是一個(gè)非接口類型的指針。
結(jié)構(gòu)體x中的嵌入字段的字段或方法叫做結(jié)構(gòu)體x的提升。對(duì)結(jié)構(gòu)體x,調(diào)用其不存在的成員或者方法,會(huì)使用嵌入字段的字段或方法來(lái)代替。
被提升的字段表現(xiàn)的就像原始字段,除了他們不能用在特殊場(chǎng)合。
給定結(jié)構(gòu)體類型和定義的類型T,提升方法包含在結(jié)構(gòu)體的方法集中。
如果S包含嵌入字段T,使用T為接受著的話,提升方法被包含在S和S的方法集合。使用T為接受者的話,提升方法被包含在*S的方法集合。
結(jié)構(gòu)體的字段后面,可以跟上一個(gè)字符串。這個(gè)字符串可以通過(guò)反射的方式獲取??梢杂糜谔厥獾膱?chǎng)合。例如json轉(zhuǎn)換,protobuf轉(zhuǎn)換。
Pointer types 指針類型
A pointer type denotes the set of all pointers to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil.
PointerType = "*" BaseType .
BaseType = Type .
*Point
*[4]int
一個(gè)指針類型表示指向給定類型所有變量的指針的類型,是指針的基礎(chǔ)類型。指針在未被初始化的時(shí)候使用nil作為初值。
Function types 函數(shù)類型
A function type denotes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is nil.
FunctionType = "func" Signature .
Signature = Parameters [ Result ] .
Result = Parameters | Type .
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] [ "..." ] Type .
Within a list of parameters or results, the names (IdentifierList) must either all be present or all be absent. If present, each name stands for one item (parameter or result) of the specified type and all non-blank names in the signature must be unique. If absent, each type stands for one item of that type. Parameter and result lists are always parenthesized except that if there is exactly one unnamed result it may be written as an unparenthesized type.
The final incoming parameter in a function signature may have a type prefixed with .... A function with such a parameter is called variadic and may be invoked with zero or more arguments for that parameter.
func()
func(x int) int
func(a, _ int, z float32) bool
func(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)
一個(gè)函數(shù)類型表示所有擁有相同參數(shù)和返回值的函數(shù)的類型。未被初始化的函數(shù)類型變量的值是nil。
在參數(shù)列表或者返回列表中,名稱必須都被顯示的聲明出來(lái),或者都沒(méi)有聲明,只寫類型。如果寫了名稱,每個(gè)名稱都有類型和非空的名字,而名字必須唯一。如果沒(méi)有聲明名字,那就只寫類型。參數(shù)和返回列表需要使用括號(hào)包裹。返回列表在只有一個(gè)類型且沒(méi)有名字時(shí)可以不加括號(hào)。
最后傳入的參數(shù)的前面可以使用可變參數(shù),前綴可以使用三個(gè)點(diǎn)。調(diào)用時(shí),需要傳入0個(gè)或以上的參數(shù)。
Interface types 接口類型
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
MethodSpec = MethodName Signature | InterfaceTypeName .
MethodName = identifier .
InterfaceTypeName = TypeName .
As with all method sets, in an interface type, each method must have a unique non-blank name.
// A simple File interface
interface {
Read(b Buffer) bool
Write(b Buffer) bool
Close()
}
More than one type may implement an interface. For instance, if two types S1 and S2 have the method set
func (p T) Read(b Buffer) bool { return … }
func (p T) Write(b Buffer) bool { return … }
func (p T) Close() { … }
(where T stands for either S1 or S2) then the File interface is implemented by both S1 and S2, regardless of what other methods S1 and S2 may have or share.
A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:
interface{}
Similarly, consider this interface specification, which appears within a type declaration to define an interface called Locker:
type Locker interface {
Lock()
Unlock()
}
If S1 and S2 also implement
func (p T) Lock() { … }
func (p T) Unlock() { … }
they implement the Locker interface as well as the File interface.
An interface T may use a (possibly qualified) interface type name E in place of a method specification. This is called embedding interface E in T; it adds all (exported and non-exported) methods of E to the interface T.
type ReadWriter interface {
Read(b Buffer) bool
Write(b Buffer) bool
}
type File interface {
ReadWriter // same as adding the methods of ReadWriter
Locker // same as adding the methods of Locker
Close()
}
type LockedFile interface {
Locker
File // illegal: Lock, Unlock not unique
Lock() // illegal: Lock not unique
}
An interface type T may not embed itself or any interface type that embeds T, recursively.
// illegal: Bad cannot embed itself
type Bad interface {
Bad
}
// illegal: Bad1 cannot embed itself using Bad2
type Bad1 interface {
Bad2
}
type Bad2 interface {
Bad1
}
接口類型表示一個(gè)方法集合,該方法集合叫做該類型的接口。接口類型可以存儲(chǔ)一個(gè)變量,以及該變量的方法集合的任何超集。傳入的類型與對(duì)應(yīng)的接口叫做該類型的實(shí)現(xiàn)。未被初始化的接口類型變量的值是nil。
和方法集合一樣,接口類型的內(nèi)部,每個(gè)方法必須油唯一非空名字。
如果S1、S2兩種類型的方法集和都包含了同樣的接口實(shí)現(xiàn),不管方法集合其他的區(qū)別是什么,S1和S2都被認(rèn)為是接口的實(shí)現(xiàn)。
如果一個(gè)類型實(shí)現(xiàn)了一個(gè)接口,這個(gè)接口的子集又是其他接口的實(shí)現(xiàn),那么這個(gè)類型也會(huì)實(shí)現(xiàn)那些接口。舉個(gè)例子,所有的類型都實(shí)現(xiàn)了空接口。
接口中也可以內(nèi)嵌其他接口,但是其內(nèi)嵌的接口的方法的名字不能沖突。
Map types 字典類型
A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil.
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.
map[string]int
map[*T]struct{ x, y float64 }
map[string]interface{}
The number of map elements is called its length. For a map m, it can be discovered using the built-in function len and may change during execution. Elements may be added during execution using assignments and retrieved with index expressions; they may be removed with the delete built-in function.
A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:
make(map[string]int)
make(map[string]int, 100)
The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.
字典類型的內(nèi)部是無(wú)序元素排序的類型,內(nèi)部的類型叫元素的類型,使用唯一鍵值進(jìn)行索引,鍵值也有另外一種類型,叫鍵類型。未被初始化的字典類型的值是nil。
鍵值類型必須完全定義了==運(yùn)算和!=運(yùn)算。因此函數(shù)、字典、切片都是不允許作為鍵值的。如果鍵值是一個(gè)接口,比較操作必須被定義為可以接受一個(gè)動(dòng)態(tài)的鍵值。對(duì)鍵值的相關(guān)操作失敗時(shí)會(huì)引發(fā)程序運(yùn)行時(shí)驚慌。
字典元素的數(shù)量稱為字典的長(zhǎng)度??梢酝ㄟ^(guò)len函數(shù)檢查,其值在運(yùn)行期間可能被更改。元素可能通過(guò)指派操作添加,可以通過(guò)下標(biāo)取出,可以通過(guò)delete函數(shù)移除。
一個(gè)空的map的值可以通過(guò)內(nèi)建函數(shù)make來(lái)創(chuàng)建,make的第一個(gè)參數(shù)是map的類型,第二個(gè)參數(shù)是容量。
字典的容量不限制大小,字典的容量會(huì)增長(zhǎng)以容納其中項(xiàng)目的數(shù)量。但nil字典不是這樣的,nil字典基本上和空字典是一樣的,除了不能添加任何元素。
Channel types 通道類型
A channel provides a mechanism for concurrently executing functions to communicate by sending and receiving values of a specified element type. The value of an uninitialized channel is nil.
ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .
The optional <- operator specifies the channel direction, send or receive. If no direction is given, the channel is bidirectional. A channel may be constrained only to send or only to receive by conversion or assignment.
chan T // can be used to send and receive values of type T
chan<- float64 // can only be used to send float64s
<-chan int // can only be used to receive ints
The <- operator associates with the leftmost chan possible:
chan<- chan int // same as chan<- (chan int)
chan<- <-chan int // same as chan<- (<-chan int)
<-chan <-chan int // same as <-chan (<-chan int)
chan (<-chan int)
A new, initialized channel value can be made using the built-in function make, which takes the channel type and an optional capacity as arguments:
make(chan int, 100)
The capacity, in number of elements, sets the size of the buffer in the channel. If the capacity is zero or absent, the channel is unbuffered and communication succeeds only when both a sender and receiver are ready. Otherwise, the channel is buffered and communication succeeds without blocking if the buffer is not full (sends) or not empty (receives). A nil channel is never ready for communication.
A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.
A single channel may be used in send statements, receive operations, and calls to the built-in functions cap and len by any number of goroutines without further synchronization. Channels act as first-in-first-out queues. For example, if one goroutine sends values on a channel and a second goroutine receives them, the values are received in the order sent.
通道提供了并行執(zhí)行程序之間的通信方式,該方式使用發(fā)送和接受特定類型的值來(lái)實(shí)現(xiàn)。未被初始化的通道的值是nil。
標(biāo)記<-用來(lái)指示通道的方向,例如是接受還是發(fā)送。如果不指定方向,則通道從是雙向的。
通道的<-標(biāo)記,轉(zhuǎn)換或指派通道的方向,成為發(fā)送或接收。
通道所傳遞的內(nèi)容也可以是通道。
使用make也可以創(chuàng)建初始化的通道,make的第二個(gè)參數(shù)可以設(shè)置通道的容量。
通道的容量是通道中元素的緩存數(shù)量。如果容量是0或者不設(shè)置,通道是沒(méi)有緩存的,只有接收者和發(fā)送者都準(zhǔn)備好時(shí)才進(jìn)行通信。否則,通道在緩存沒(méi)有滿時(shí),是不阻塞的。如果通道的值是0,則永遠(yuǎn)無(wú)法通信。
通道使用系統(tǒng)調(diào)用close來(lái)關(guān)閉。使用多值接受的第二個(gè)參數(shù)來(lái)判斷通道是否關(guān)閉。
單向通道用于發(fā)送表達(dá)式,接收操作。cap與len也可以調(diào)用,并且無(wú)須擔(dān)心多個(gè)同步的協(xié)程同時(shí)運(yùn)行。通道是先入先出的,如果第一個(gè)協(xié)成放入了一個(gè)值,第二個(gè)協(xié)成取出的一定是先放入的值。