您的位置:首页 > 编程语言 > Go语言

Go 的 类型定义 和 类型别名 (Type Alias Declarations)

2021-08-18 00:06 519 查看
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)
}

btw,

byte
uint8
的 alias ,
rune
int32
的 alias

reference: https://go101.org/article/type-system-overview.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: