您的位置:首页 > 编程语言 > Go语言

Golang学习笔记:语言规范之类型(续)

2015-10-17 11:45 507 查看

类型(续)

指针类型

指针类型表示所有给定类型的指针变量,也称为基础类型的指针,默认未初始化的指针类型值为
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) 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)


接口类型

接口类型表示一组方法的组合。接口类型的变量可以存储引用任意类型T,只要T的方法都实现该接口的方法,这样的T类型可以被称为实现了该接口,未初始化的接口类型变量值为
nil


InterfaceType   = "interface" "{" { MethodSpec ";" } "}"
MethodSpec       = MethodName Signature | InterfaceTypeName
MethodName         = identifier
InterfaceTypeName  = TypeName


接口的所有方法必须是唯一的非空白名称

// A simple File interface
interface {
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 itself
type 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]int
map[*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 T
chan<- float64  // can only be used to send float64s
<-chan int      // can only be used to receive ints


使用
make
方法来创建管道


make(chan int, 100)


最后一个参数表示容量,可以省略。定义了该参数,表示此管道是一个缓冲管道,因此该管道只能存储指定的大小的元素,当超出长度后,则会阻塞,直到goroutine从管道中读取一些元素,腾出空间。

可用
close
函数来关闭管道。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: