GO语言基础教程13——结构体-类型别名和自定义类型

434 阅读1分钟

GO语言基础教程13——结构体-类型别名和自定义类型

自定义类型

在Go语言中有一些基本的数据类型,如string整型浮点型布尔等数据类型, Go语言中可以使用type关键字来定义自定义类型。

例如:

type MyInt int

通过type关键字的定义,MyInt就是一种新的类型,它具有int的特性。

类型别名

我们之前见过的runebyte就是类型别名,他们的定义如下:

type byte = uint8
type rune = int32

自定义类型和类型别名的区别

自定义类型是将目标类型等同复制过来,而类型别名只是在使用改数据类型是可以使用的名字。

//类型定义
type NewInt int

//类型别名
type MyInt = int

func main() {
	var a NewInt
	var b MyInt	
	fmt.Printf("type of a:%T\n", a) //type of a:main.NewInt
	fmt.Printf("type of b:%T\n", b) //type of b:int
}

(点击进入专栏查看详细教程)