go 类型系统(二)

来源:互联网 发布:打电话软件 编辑:程序博客网 时间:2024/06/07 10:20

pre-declared type (预声明类型)

golang 默认的有几个预声明类型:boole,num,string type. 这些预声明类型被用来构造其他的类型。

type literal(字面量类型)

由其他预声明类型组合而成(没有使用type 关键字定义),array,struct,pointer,slice,map,channel,function,interface

[2]int ,[ ] int , chan int , map[string] string ,* int 

注意:type literal 中的struct,interface 特指匿名的类型,没有使用type包装,

命名类型和非命名类型

named type : 一个类型通过一个标识符标示就是命类型名字(type name)

unamed type一个类型是由先前已声明类型组合构成被称为类型字面量(type literal)


二者区别:

named type 可以有自己的methods, mehtods 是一种特殊形式的函数,该函数的第一个参数是该type的变量或指向该类型变量的指针(receiver.

unamed type:不能定义自己的method

type

包括

特点

named type

pre-declared

type declared new type

可以定义自己的method

unamed type 

type literal 

不可以定义自己的method


一个特别重要的事情需要记住:pre-declared types 也是命名类型。所以:int named type , 但是 *int ,[]int 不是。

特别注意:我们不能直接为int 定义method

func (a int) methodname() {

}

不是因为int unnamed type ,而是为一个type定义方法必须在该类型的所在的package , int scope (作用域是)universe (全局的)int 是语言层面预声明的,其属于任何package,也就没有办法为其增加method.

package mainimport (        "fmt")func (a int) Print() {        fmt.Println(a)}func main() {          m := 12          a.Print()}[root@tata.domain /project/go/src/test]#go build name.go # command-line-arguments./name.go:7: cannot define new methods on non-local type int./name.go:13: undefined: a


 Underlying Type 底层类型

所有type(类型)都有个underlying type(底层类型)Pre-declared types type literals 的底层类型是它们自身;通过type newtype oldtype 的底层类型,是逐层递归向下查找的,直到查到的oldtype Pre-declared types type literals

type

underlying type

示例

pre-declared type 

itself

string underlying type 还是string

type literal

itself

map[string]stringunderlying type 还是map[string]string

通过type定义的新类型:

type newtype oldtype

逐层向下递归查找oldtype,直到oldtypepre-declared type type literal;找到的pre-declared type type literal就是underlying type

  type Map map[string]string

  type SpecialMap Map

则:Map 和 SpecialMap underlying type 

都是map[string]string



另一条重要规则是:

type newtype oldtype:  newtype不会从oldtype或其underlying type继承任何methods .

有两个特例就是:接口和组合类型(composite type)

new type

Methods SET

type interface2 interface1

interface2 会继承interface1methods set

type NewType struct {

InnerType

}

NewType 会继承InnerTypemethods set

其他type newtype oldtype

newtype 不会从oldtype 或其underlying type中继承任何方法

这里表达的意思就是:一旦你定义一个新类型,你往往是想为其定义一个新的methods set 


static type 静态类型和dynamic type 动态类型

static type就是变量定义声明是的类型,

只有interface 有动态类型
接口类型变量有dynamic type,接口的动态类型是其在运行时绑定值的类型
接口的动态类型可以在运行时发生变化,但是动态类型其必须满足可以赋值给接口类型的条件,否则会发生panic;

非interface 的类型的dynamic type 就是其static type

static type就是变量定义声明是的类型,接口类型变量还有个dynamic type,接口的动态类ixngshi在运行时其存储的值的类型,接口的动态类型可以变化,但是其必须满足可以赋值给接口类型的规则;对于非接口类型,动态类型就是静态类型。



0 0
原创粉丝点击