type A = B // type alias             仅仅是一个 alias (别名), 没有生成一个新的 type,因此不需要强转型
type A B // type definition, 将会产生一个新的 type, 在进行类型变换时,需要强转型
package main

import "fmt"

type A = int
type B int

func main() {
var a A
var b B
var i int

a = i
b = B(i)
fmt.Println(a, b)
}


使用 type alias 之后,不一定能为该 type alias 添加 method。

例如在上面 A 是 int 的 alias,也就是说 A 实际上就是 int,int 是一个 built in type ,在 go 中没办法为 build in type 添加 alias。

func (A) Hello() {
// Error : Cannot define new methods on the non-local type 'builtin.int'
}

func (B) Hello() {
// It's OK
}


type alias 和它的本体的 method 定义是共享的

package main

import "fmt"

type B int
type AliasB = B

func (B) Hello() {
fmt.Println("hello")
}

// func (AliasB) Hello() {
// // Error: Method redeclared 'AliasB.Hello'
// }

func (AliasB) World() {
fmt.Println("world")
}

func main() {
var b B
var aliasB AliasB
b.Hello() // ok
b.World() // ok
aliasB.Hello() // ok
aliasB.World() // ok
}


method 的 receiver 的 type 不能是 pointer, 因此下面两种做法都是编译不过的

type B int
type AliasB = B
type AliasPointerB = *B
type PointerB *B

func (PointerB) Hello() {
// Error: Invalid receiver type 'PointerB' ('PointerB' is a pointer type)
}

func (AliasPointerB) PHello() {
// Error: Invalid receiver type 'AliasPointerB' ('AliasPointerB' is a pointer type)
}


​byte​​uint8​​rune​​int32​