类型别名:Type Alias
区分类型别名与类型定义
类型别名的写法为:
type TypeAlias = Type
代码如下:
package main
import (
"fmt"
)
type NewInt int
type IntAlias = int
func main() {
var a NewInt
fmt.Printf("a type: %T\n", a)
var a2 IntAlias
fmt.Printf("a2 type: %T\n", a2)
}
运行结果如下:
a type: main.NewInt
a2 type: int
非本地类型不能定义方法
在结构体成员嵌入时使用别名
代码如下:
package main
import (
"fmt"
"reflect"
)
type Brand struct {
}
type (t Brand) Show() {
}
type FakeBrand = Brand
type Vehicle struct{
FakeBrand
Brand
}
func main() {
var a Vehicle
a.FakeBrand.Show()
ta:=reflect.TypeOf(a)
for i:=0;i<ta.NumField();i++{
f:=ta.Field(i)
fmt.Printf("FieldName: %v, FieldType: %v\n",f.Name, f.Type.Name())
}
}
运行结果如下:
# command-line-arguments
test/basic.go:12:16: syntax error: unexpected Show after top level declaration
界面值:
代码如下:
package main
import (
"fmt"
)
type Duck float32
func (Duck) Quack() string {
return "嘎"
}
type Educk complex128
func (Educk) Quack() string {
return "叮咚"
}
type Quacker interface {
Quack() string
}
func main() {
var d Duck = 0.
var e Educk = 0i
var q Quacker
fmt.Println(d, e, q)
q = d
fmt.Println(q.Quack())
q = e
fmt.Println(q.Quack())
}
运行结果如下:
0 (0+0i) <nil>
嘎
叮咚
代码如下:
package main
import (
"fmt"
)
type A struct {
Face int
}
type Aa = A // 类型别名
func (a A) f() {
fmt.Println("hi ", a.Face)
}
func main() {
var s A = A{Face: 9}
s.f()
var sa Aa = Aa{Face: 9}
sa.f()
}
运行结果如下:
hi 9
hi 9