类型别名
为类型起个别名,方便代码编写过程中使用。
type alias = T
type
:关键字、alias
:类型别名、T
:类型
例如数据类型中提到的Unicode字符型 rune
和ASCII字符型 byte
就是类型别名
type rune = int32
type byte = uint8
自定义类型
在 Go 中有一些基本的数据类型,如string
、int
、bool
等数据类型,也可以通过关键字 type
来定义自定义类型
自定义类型是定义了一个全新的类型,我们可以基于内置基本类型定义,也可以通过 struct 定义。
eg:
type Status bool
通过 type
关键字的定义,Status
就是一种新的类型,它具有 bool
的特性
区别
从定义上看,类型别名有 =
,自定义类型没有。
func main() {
type abc = string
type Status bool
var OK Status
var ss abc
fmt.Printf("Type of OK: %T\n", OK) // Type of OK: main.Status
fmt.Printf("Type of ss: %T\n", ss) // Type of ss: string
}
OK 的类型是 main.Status,表示在 main 包下定义的Status
类型
ss 的类型是 string。abc
类型只会在代码中存在,编译前编译器会将其替换回来。