多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 自定义类型 Go语言中可以使用`type`关键字来定义自定义类型。 ~~~go //将MyInt定义为int类型 type MyInt int ~~~ 通过`type`关键字的定义,`MyInt`就是一种新的类型,它具有`int`的特性。 ## 类型别名 ~~~go type TypeAlias = Type ~~~ `rune`和`byte`就是类型别名,定义如下: ~~~go type byte = uint8 type rune = int32 ~~~ ## 类型定义和类型别名的区别 ~~~go //类型定义 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`类型。