type byte uint8 type rune int32而在 Go 1.9 版本之后变为:
type byte = uint8 type rune = int32这个修改就是配合类型别名而进行的修改。
type TypeAlias = Type
类型别名规定:TypeAlias 只是 Type 的别名,本质上 TypeAlias 与 Type 是同一个类型,就像一个孩子小时候有小名、乳名,上学后用学名,英语老师又会给他起英文名,但这些名字都指的是他本人。package main import ( "fmt" ) // 将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 // 查看a2的类型名 fmt.Printf("a2 type: %T\n", a2) }代码运行结果:
a type: main.NewInt
a2 type: int
%T
格式化参数,打印变量 a 本身的类型。package main import ( "time" ) // 定义time.Duration的别名为MyDuration type MyDuration = time.Duration // 为MyDuration添加一个函数 func (m MyDuration) EasySet(a string) { } func main() { }代码说明如下:
cannot define new methods on non-local type time.Duration
编译器提示:不能在一个非本地的类型 time.Duration 上定义新方法,非本地类型指的就是 time.Duration 不是在 main 包中定义的,而是在 time 包中定义的,与 main 包不在同一个包中,因此不能为不在一个包中的类型定义方法。package main import ( "fmt" "reflect" ) // 定义商标结构 type Brand struct { } // 为商标结构添加Show()方法 func (t Brand) Show() { } // 为Brand定义一个别名FakeBrand type FakeBrand = Brand // 定义车辆结构 type Vehicle struct { // 嵌入两个结构 FakeBrand Brand } func main() { // 声明变量a为车辆类型 var a Vehicle // 指定调用FakeBrand的Show a.FakeBrand.Show() // 取a的类型反射对象 ta := reflect.TypeOf(a) // 遍历a的所有成员 for i := 0; i < ta.NumField(); i++ { // a的成员信息 f := ta.Field(i) // 打印成员的字段名和类型 fmt.Printf("FieldName: %v, FieldType: %v\n", f.Name, f.Type. Name()) } }代码输出如下:
FieldName: FakeBrand, FieldType: Brand
FieldName: Brand, FieldType: Brand
a.Show()
编译器将发生报错:ambiguous selector a.Show
在调用 Show() 方法时,因为两个类型都有 Show() 方法,会发生歧义,证明 FakeBrand 的本质确实是 Brand 类型。Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有