自定义类型
在Go语言中有一些基本的数据类型,如string
、整型
、浮点型
、布尔
等数据类型, Go语言中可以使用type
关键字来定义自定义类型。
type MyInt int
type MyFunc fun(int, int)int
type scoreMap map[string]int
通过type
关键字的定义,MyInt
就是一种新的类型,它具有int
的特性。
自定义类型是程序员根据自己的需要创造的新类型。
类型别名
让代码更易读
type NewInt = int
内置的byte
和rune
就是类型别名
type byte = uint8
type rune = int32
自定义类型和类型别名区别
类型别名类型定义表面上看只有一个等号的差异,我们通过下面的这段代码来理解他们之间的区别。
//类型定义
type NewInt int
//类型别名
type MyInt = int
func t1() {
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
}
//运行结果:
type of a: main.NewInt
type of b: int
结果显示的是main.NewInt
类型,表示main
包下定义的NewInt
类型。b的类型为int
。
类型别名只在源文件中生效,编译时会被替换成原始类型。
类型显式转换
func t2() {
var x MyInt = 100
fmt.Printf("x: %T\n", x) //int
var y NewInt = 100
fmt.Printf("y: %T\n", y) //main.NewInt
x = MyInt(y) //类型强制转换
y = NewInt(x) //强制类型转换
f := 1.123
i := int(f) //浮点数可以强制类型转换为整数,但是会丢失精度。
fmt.Println(i)
}
//运行结果:
x: int
y: main.NewInt
1