程序员

Go语言的类型系统概览

2019-03-10  本文已影响0人  golang推广大使

本文将介绍go语言中的各种类型和go类型系统中的各种概念。 不知道这些概念,将很难理解go语言。

概念:基本类型

go语言中的内置类型已经在《内置基本类型和基本值》中介绍过了。为了本文的完整性,在此再次列出内置的基本类型

概念: 组合类型

Go 支持下面的组合类型:

复合类型可以表示为它们各自的类型文字。以下是各种复合类型的一些文字表示示例。

// Assume T is an arbitrary type and Tkey is
// a type supporting comparison (== and !=).

*T         // a pointer type
[5]T       // an array type
[]T        // a slice type
map[Tkey]T // a map type

// a struct type
struct {
    name string
    age  int
}

// a function type
func(int) (bool, string)

// an interface type
interface {
    Method0(string) int
    Method1() (int, bool)
}

// some channel types
chan T
chan<- T
<-chan T

事实:各种类型

上述基本和复合类型中的每一种对应于一种类型。除了这些类型之外,unsafe包中引入的unsafe 指针类型也属于一种类型。
到目前为止(go1.12)go有26种类型。

语法:类型定义

在go语言中,我们可以通过下面的方式定义新的类型。在语法上type是个关键词。

type NewTypeName SourceType
type (
  NewTypeName1 SourceType1
  NewTypeName2 SourceType2
)

新的类型名字必须是个标识符。
上例中的第二种类型声明包括两种类型规范。如果类型声明包含多个类型规范,则类型规范必须包含在一对()中。
注意:

一些类型定义的例子:

// The following new defined and source types are all basic types.
type (
    MyInt int
    Age   int
    Text  string
)

// The following new defined and source types are all composite types.
type IntPtr *int
type Book struct{author, title string; pages int}
type Convert func(in0 int, in1 bool)(out0 int, out1 string)
type StringArray [5]string
type StringSlice []string

func f() {
    // The names of the three defined types
    // can be only used within the function.
    type PersonAge map[string]int
    type MessageQueue chan string
    type Reader interface{Read([]byte) int}
}

语法:类型别名声明

type (
Name = string
Age = int 
)
type table = map[string]int
type Table = map[Name]Age

概念: 定义的类型和非定义的类型

一个定义的类型是一个在类型定义或者类型别名中定义的。
所有的基本类型都是定义的。非定义类型一定是组合类型。
在下面的例子中,别名类型C和类型文字[]string 都是非定义类型,但是类型A和B都是定义类型

type A []string
type B = A
type C = []string

概念:命名类型和匿名类型

在go语言中:

概念: 标的类型

在go语言中,每个类型都有一个标的类型。规则是:

例如:

// The underlying types of the following ones are both int.
type (
    MyInt int
    Age   MyInt
)

// The following new types have different underlying types.
type (
    IntSlice = []int   // underlying type is []int
    MyIntSlice []MyInt // underlying type is []MyInt
    AgeSlice   []Age   // underlying type is []Age
)

// The underlying types of Ages and AgeSlice are both []Age.
type Ages AgeSlice

给出一个声明的类型,如何追踪它的标的类型呢?规则是,当遇到一个内置基本类型,unsafe.Pointer 或者匿名类型时,和追踪将被终止。以上面的类型声明为例,我们追踪一下他们的标的类型。

MyInt → int
Age → MyInt → int
IntSlice → []int
MyIntSlice → []MyInt → []int
AgeSlice → []Age → []MyInt → []int
Ages → AgeSlice → []Age → []MyInt → []int

在go语言中:

概念: 值

一个类型的实例被成为这种类型的一个值。
每种类型都有一个0值

概念: 值部件

每个值部件占领一段连续的内存,间接标的部件被他的直接部件通过指针引用。

在运行时,很多值都是存在内存中的。在go中,每个这种值都有一个直接的部件。然而有些有一个或者多个间接部件。

上一篇 下一篇

猜你喜欢

热点阅读