Golang 中类型别名就是为已存在的 类型 定义一个别名。Golang 中类型别名使用 type 关键字来定义。
type TypeAlias = Type
参数 | 描述 |
---|---|
type | 定义类型别名使用的关键字。 |
TypeAlias | Type 的别名。 |
Type | 需要起别名的类型。 |
Go 语言类型别名是 Go 1.9 之后的版本才有的功能。TypeAlias 只是 Type 的别名,本质上 TypeAlias 与 Type 是同一个类型。
type TypeAlias Type
参数 | 描述 |
---|---|
type | 定义类型别名使用的关键字。 |
TypeAlias | Type 的别名。 |
Type | 需要起别名的类型。 |
Go 语言类型定义是 Go 一直具有的功能。Go 语言类型定义与 Go 语言类型别名定义方式仅相差一个 = 号。
使用 type 关键字定义类型别名
package main
import (
"fmt"
)
type Error = int
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 使用 type 定义类型别名
var err Error
err = 10001
fmt.Printf("err = %d, err type = %T\n", err, err)
}
程序运行,结果如下:
首先,我们使用 type 给 int 类型定义了类型别名为 Error。接着,我们定义了一个 Error 类型的变量,并赋值。
最后,我们打印出 变量 err 的值和其值所对应的类型,可以看到其类型为 int,所以本质上类型别名其实和原始的类型是同一个类型。
使用 type 关键字实现类型定义
package main
import (
"fmt"
)
type Error int
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 使用 type 实现类型定义
var err Error
err = 10001
fmt.Printf("err = %d, err type = %T\n", err, err)
}
程序运行,结果如下:
首先,我们使用 type 定义了一个新的类型 Error。接着,我们定义了一个 Error 类型的变量,并赋值。
最后,我们打印出变量 err 的值和其值所对应的类型,可以看到其类型为 main.Error,所以本质上类型定义和原始的类型不是同一个类型。
Golang 中类型别名使用 type 关键字来定义。Go 语言类型别名是 Go 1.9 之后的版本才有的功能,本质上类型别名其实和原始的类型是同一个类型。
Go 语言类型定义是 Go 一直具有的功能,本质上 类型定义 和原始的类型不是同一个类型。