37

Golang 之区分类型别名与类型定义

 4 years ago
source link: https://www.tuicool.com/articles/Z3iA7fR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、类型别名

type byte=uint8 type rune=int32

二、区别类型别名和类型定义

// 自定义类型myInt,基本类型是int

type myInt int

//将 int 类型取一个别名intAlias

type intAlias = int

func main() {

var a myInt 

//声明 a变量为自定义 myInt 类型

fmt.Printf("a Type: %T, value: %d\n", a, a) 

// 输出 a 的类型和默认值

var b intAlias 

//声明 b变量为 intAlias 类型

fmt.Printf("b Type: %T, value: %d\n", b, b)

// 输出 b 的类型和默认值

}

== 输出结果 ==

a Type: main.myInt, value: 0
b Type: int, value: 0

从上面的结果我们可以看出:

a 的类型是  main.myInt,表示main 包下定义的myInt 类型
b  的类型是 int 。intAlias 类型只会在代码中存在,编译完成时,不会有 intAlias 类型

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK