Go類(lèi)型官方參考 中英文對(duì)照

官方參考

https://golang.org/ref/spec#Types

其中類(lèi)型有:

Method sets 方法集合
Boolean types 布爾類(lèi)型
Numeric types 數(shù)字類(lèi)型
String types 字符串類(lèi)型
Array types 數(shù)組類(lèi)型
Slice types 切片類(lèi)型
Struct types 結(jié)構(gòu)體類(lèi)型
Pointer types 指針類(lèi)型
Function types 函數(shù)類(lèi)型
Interface types 接口類(lèi)型
Map types 字典類(lèi)型
Channel types 通道類(lèi)型

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.

接口類(lèi)型Interface types的接口就是方法集合资溃。若一組方法的接受參數(shù)都為參數(shù)T洗做,把這組方法叫T類(lèi)型的方法集合纪蜒。T指針的對(duì)應(yīng)方法集合足丢,其接受參數(shù)為T(mén)或者*T。這意味著T指針的方法集合包含T類(lèi)型的方法集合。對(duì)結(jié)構(gòu)體來(lái)說(shuō),該規(guī)則同樣適用。任何類(lèi)型都有一個(gè)空的方法集合徙菠。在方法集合中,每個(gè)方法都有一個(gè)非空的方法名稱(chēng)郁岩。

類(lèi)型的方法集合確定了該類(lèi)型實(shí)現(xiàn)的接口婿奔,以及可以可以被該類(lèi)型的接收器調(diào)用的方法缺狠。

Boolean types 布爾類(lèi)型

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.

布爾類(lèi)型定義了布爾變量,可被賦值為常量true和false萍摊。該類(lèi)型是已定義類(lèi)型挤茄。例如可以使用char類(lèi)型來(lái)定義。

Numeric types 數(shù)字類(lèi)型

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ù)字類(lèi)型包括整型和浮點(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ù)字類(lèi)型為已定義類(lèi)型逼龟,而byte是uint8的別名评凝,rune是int32的別名。在數(shù)字類(lèi)型之間的轉(zhuǎn)換需要進(jìn)行顯示轉(zhuǎn)換腺律。

String types 字符串類(lèi)型

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.

字符串類(lèi)型可以表示所有字符串的值肥哎。一個(gè)字符串的值是一系列空或不空的字節(jié)序列。他的值不能被修改疾渣。字符串被創(chuàng)建后就不能修改內(nèi)容。我們使用string來(lái)聲明一個(gè)string類(lèi)型崖飘。string類(lèi)型是已定義類(lèi)型榴捡。

一個(gè)字符串的長(zhǎng)度(其包含多少個(gè)字節(jié))可以使用內(nèi)建函數(shù)len來(lái)計(jì)算。在編譯器可以計(jì)算一個(gè)常量string的長(zhǎng)度朱浴。string類(lèi)型的變量可以訪問(wèn)其位置0到位置len-1的值吊圾。對(duì)這些位置的元素,獲取其地址是非法的翰蠢。使用s[i]表示s字符串第i個(gè)位置的元素项乒,而&s[i]是非法的。

Array types 數(shù)組類(lèi)型

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ù)組類(lèi)型是多個(gè)同類(lèi)型的元素構(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ù)組類(lèi)型永遠(yuǎn)是一維的,進(jìn)行組合可以表示多位類(lèi)型施敢。

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)狭莱。切片的類(lèi)型表示其元素的類(lèi)型。未初始化的切片的值為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)建指定類(lèi)型的切片栽燕。make接受切片類(lèi)型和切片的長(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 field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
  • If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T 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è)字段有自己的名稱(chēng)和類(lèi)型。類(lèi)型可以隱式指定辩棒。在結(jié)構(gòu)中非空字段名稱(chēng)必須是唯一的狼忱。

結(jié)構(gòu)體可以為空。也可以包含int float等類(lèi)型一睁。如果使用_表示padding占位藕赞。

如果結(jié)構(gòu)體的字段只有類(lèi)型而沒(méi)有名字,我們表示這個(gè)字段是嵌入字段卖局。嵌入字段的類(lèi)型必須是類(lèi)型T斧蜕,或者是一個(gè)非接口類(lèi)型的指針。

結(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)體類(lèi)型和定義的類(lèi)型T,提升方法包含在結(jié)構(gòu)體的方法集中掀宋。

如果S包含嵌入字段T深纲,使用T為接受著的話(huà),提升方法被包含在S和S的方法集合劲妙。使用T為接受者的話(huà)湃鹊,提升方法被包含在*S的方法集合。

結(jié)構(gòu)體的字段后面镣奋,可以跟上一個(gè)字符串币呵。這個(gè)字符串可以通過(guò)反射的方式獲取∏染保可以用于特殊的場(chǎng)合余赢。例如json轉(zhuǎn)換,protobuf轉(zhuǎn)換哈垢。

Pointer types 指針類(lèi)型

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è)指針類(lèi)型表示指向給定類(lèi)型所有變量的指針的類(lèi)型妻柒,是指針的基礎(chǔ)類(lèi)型。指針在未被初始化的時(shí)候使用nil作為初值耘分。

Function types 函數(shù)類(lèi)型

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ù)類(lèi)型表示所有擁有相同參數(shù)和返回值的函數(shù)的類(lèi)型举塔。未被初始化的函數(shù)類(lèi)型變量的值是nil。

在參數(shù)列表或者返回列表中陶贼,名稱(chēng)必須都被顯示的聲明出來(lái),或者都沒(méi)有聲明待秃,只寫(xiě)類(lèi)型拜秧。如果寫(xiě)了名稱(chēng),每個(gè)名稱(chēng)都有類(lèi)型和非空的名字章郁,而名字必須唯一枉氮。如果沒(méi)有聲明名字,那就只寫(xiě)類(lèi)型暖庄。參數(shù)和返回列表需要使用括號(hào)包裹聊替。返回列表在只有一個(gè)類(lèi)型且沒(méi)有名字時(shí)可以不加括號(hào)。

最后傳入的參數(shù)的前面可以使用可變參數(shù)培廓,前綴可以使用三個(gè)點(diǎn)惹悄。調(diào)用時(shí),需要傳入0個(gè)或以上的參數(shù)肩钠。

Interface types 接口類(lèi)型

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
}

接口類(lèi)型表示一個(gè)方法集合泣港,該方法集合叫做該類(lèi)型的接口暂殖。接口類(lèi)型可以存儲(chǔ)一個(gè)變量,以及該變量的方法集合的任何超集当纱。傳入的類(lèi)型與對(duì)應(yīng)的接口叫做該類(lèi)型的實(shí)現(xiàn)呛每。未被初始化的接口類(lèi)型變量的值是nil。

和方法集合一樣坡氯,接口類(lèi)型的內(nèi)部晨横,每個(gè)方法必須油唯一非空名字。

如果S1箫柳、S2兩種類(lèi)型的方法集和都包含了同樣的接口實(shí)現(xiàn)手形,不管方法集合其他的區(qū)別是什么,S1和S2都被認(rèn)為是接口的實(shí)現(xiàn)滞时。

如果一個(gè)類(lèi)型實(shí)現(xiàn)了一個(gè)接口叁幢,這個(gè)接口的子集又是其他接口的實(shí)現(xiàn),那么這個(gè)類(lèi)型也會(huì)實(shí)現(xiàn)那些接口坪稽。舉個(gè)例子曼玩,所有的類(lèi)型都實(shí)現(xiàn)了空接口。

接口中也可以?xún)?nèi)嵌其他接口窒百,但是其內(nèi)嵌的接口的方法的名字不能沖突黍判。

Map types 字典類(lèi)型

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.

字典類(lèi)型的內(nèi)部是無(wú)序元素排序的類(lèi)型,內(nèi)部的類(lèi)型叫元素的類(lèi)型篙梢,使用唯一鍵值進(jìn)行索引顷帖,鍵值也有另外一種類(lèi)型,叫鍵類(lèi)型渤滞。未被初始化的字典類(lèi)型的值是nil贬墩。

鍵值類(lèi)型必須完全定義了==運(yùn)算和!=運(yùn)算妄呕。因此函數(shù)陶舞、字典、切片都是不允許作為鍵值的绪励。如果鍵值是一個(gè)接口肿孵,比較操作必須被定義為可以接受一個(gè)動(dòng)態(tài)的鍵值。對(duì)鍵值的相關(guān)操作失敗時(shí)會(huì)引發(fā)程序運(yùn)行時(shí)驚慌疏魏。

字典元素的數(shù)量稱(chēng)為字典的長(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的類(lèi)型,第二個(gè)參數(shù)是容量蜀变。

字典的容量不限制大小悄谐,字典的容量會(huì)增長(zhǎng)以容納其中項(xiàng)目的數(shù)量。但nil字典不是這樣的库北,nil字典基本上和空字典是一樣的爬舰,除了不能添加任何元素。

Channel types 通道類(lèi)型

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)型的值來(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)有滿(mǎn)時(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é)成取出的一定是先放入的值涂乌。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末艺栈,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子湾盒,更是在濱河造成了極大的恐慌湿右,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,013評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罚勾,死亡現(xiàn)場(chǎng)離奇詭異毅人,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)尖殃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,205評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)丈莺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人送丰,你說(shuō)我怎么就攤上這事缔俄。” “怎么了器躏?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,370評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵俐载,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我邀桑,道長(zhǎng)瞎疼,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,168評(píng)論 1 278
  • 正文 為了忘掉前任壁畸,我火速辦了婚禮贼急,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘捏萍。我一直安慰自己太抓,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,153評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布令杈。 她就那樣靜靜地躺著走敌,像睡著了一般。 火紅的嫁衣襯著肌膚如雪逗噩。 梳的紋絲不亂的頭發(fā)上掉丽,一...
    開(kāi)封第一講書(shū)人閱讀 48,954評(píng)論 1 283
  • 那天,我揣著相機(jī)與錄音异雁,去河邊找鬼捶障。 笑死,一個(gè)胖子當(dāng)著我的面吹牛纲刀,可吹牛的內(nèi)容都是我干的项炼。 我是一名探鬼主播,決...
    沈念sama閱讀 38,271評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼锭部!你這毒婦竟也來(lái)了暂论?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,916評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤拌禾,失蹤者是張志新(化名)和其女友劉穎取胎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體湃窍,經(jīng)...
    沈念sama閱讀 43,382評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡扼菠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,877評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了坝咐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片循榆。...
    茶點(diǎn)故事閱讀 37,989評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖墨坚,靈堂內(nèi)的尸體忽然破棺而出秧饮,到底是詐尸還是另有隱情,我是刑警寧澤泽篮,帶...
    沈念sama閱讀 33,624評(píng)論 4 322
  • 正文 年R本政府宣布盗尸,位于F島的核電站,受9級(jí)特大地震影響帽撑,放射性物質(zhì)發(fā)生泄漏泼各。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,209評(píng)論 3 307
  • 文/蒙蒙 一亏拉、第九天 我趴在偏房一處隱蔽的房頂上張望扣蜻。 院中可真熱鬧,春花似錦及塘、人聲如沸莽使。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,199評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)芳肌。三九已至,卻和暖如春肋层,著一層夾襖步出監(jiān)牢的瞬間亿笤,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,418評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工栋猖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留净薛,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,401評(píng)論 2 352
  • 正文 我出身青樓掂铐,卻偏偏與公主長(zhǎng)得像罕拂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子全陨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,700評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,292評(píng)論 0 10
  • 【大型網(wǎng)站技術(shù)實(shí)踐】初級(jí)篇:借助LVS+Keepalived實(shí)現(xiàn)負(fù)載均衡
    myang199088閱讀 245評(píng)論 0 5
  • 昨天一早七點(diǎn)從京出發(fā)爆班,一路向南,車(chē)行至江蘇境內(nèi)辱姨,已經(jīng)下午柿菩,在鹽城附近開(kāi)始堵車(chē),一路車(chē)禍多起雨涛,看著導(dǎo)航上全程綠色進(jìn)度...
    任亞閱讀 154評(píng)論 0 1
  • 嗯枢舶,我可以是一個(gè)大學(xué)生了,我可以走出 去了替久,雖然沒(méi)有走太遠(yuǎn)凉泄。但我最重要的生 活開(kāi)始了。 它進(jìn)行的并不順利蚯根。我渴望著...
    微塵記浮生閱讀 201評(píng)論 0 0