go语言中可以使用type关键字来定义类型,type有关类型方面有两种发放,一种是类型别名,一种是自定义类型。
type myInt int //自定义类型
type thisInt = int //类型别名
自定义类型myInt
是一种新的类型,具有int的特性
类型别名是Go1.9
版本添加的功能,本质上thisInt
与int
是同一个类型。相当于外号。
例如byte与rune
type byte = uint8
type rune = int32
区别
package main
type myInt int //自定义类型
type thisInt = int //类型别名
func main() {
var num int
var a myInt
var b thisInt
fmt.Printf("type of a:%T\n", a) //type of a:main.myInt
fmt.Printf("type of b:%T\n", b) //type of b:int
fmt.Println(a == num) //报错,不同类型之间不可以比较
fmt.Println(b == num) //不报错
}