自定义类型
使用
type
关键字来定义自定义类型
//自定义类型是定义了一个全新的类型
// 1. 基于内置的基本类型定义
// 2. 通过struct定义
//将MyInt类型定义为int类型
type MyInt int
类型别名
类型别名只是对一个类型,进行另起一个名字
//定义的语法
type TypeAlias = Type
//之前使用过的类型别名有
type byte = uint8
type rune = int32
var c rune
c = '中'
fmt.Println(c)
fmt.Printf("%T\n", c)
区别
类型别名只存在在代码编写过程中,编译后恢复原来类型
//类型定义
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
}
结果显示a的类型是main.NewInt,表示main包下定义了一个NewInt类型,b的类型是int,MyInt类型只会在代码中存在,编译完成后并不会存在MyInt类型