<5>Golang基础进阶——类型别名

Golang:类型别名

1. 区分类型别名与类型定义

类型别名的写法为:

type TypeAlias = Type

类型别名规定:TypeAlias 只是 Type 的别名,本质上TypeAlias与Type 是同一个类型。就像一个孩子小时候有小名、乳名,上学后用学名,英语老师又会给他起英文名,但这些名字都指的是他本人。

类型别名和类型定义代码示例:

// NewInt 定义为int类型
type NewInt int

// int 个别名IntAlias
type IntAlias = int

func main() {
// a声明为NewInt类型
var a NewInt
// 查看a的类型名
fmt.Printf("a type: %T\n", a)

// a2声明为IntAlias类型
var a2 IntAlias
fmt.Printf("a2 type: %T\n", a2)

}

// 输出结果:
//a type: main.NewInt
//a2 type: int

结果显示a类型是 main.NewInt 表示 main 包下定义的 NewInt 类型。 a2 类型是 int。IntAlias 类型只会在代码中存在,编译完成时,不会有 IntAlias 类型。

2. 非本地类型不能定义方法

能够随意地为各种类型起名字,是否意味着可以在自己包里为这些类型任意添加方法?

// 定义time.Duration的别名为MyDuration
type MyDuration = time.Duration

func (m MyDuration) EasySet(a string) {

}

func main() {

}

// 输出结果:
//cannot define new methods on non-local type time.Duration

编译器提示:不能在一个非本地的类型 time.Duration 上定义新方法。
 time.Duration 在time包中,但是在main包中定义是不允许的。

解决方法:

1. 将别名修改为类型定义:type MyDuration time.Duration。

2. 将MyDutation的别名定义放在time包中。

 

posted @ 2020-04-11 12:54  Wshile  阅读(457)  评论(0编辑  收藏  举报