go语言type类型,定义类型别名
go语言中,type主要用来定义类型,比如结构体、接口等等,初级的用法就是常常用来定义类型的别名,这样讲可能有些抽象,我们直接用实例吧。
type定义类型别名
语法如下:
type 自定义类型名称 底层类型名称
package main
import "fmt"
type zhengxing int
type zifuchuanliebiao []string
func main() {
var a zhengxing = 1
fmt.Printf("变量a的类型为%T,值为%v \n", a, a)
var b zifuchuanliebiao = []string{"c", "d", "e"}
fmt.Printf("变量b的类型为%T,值为%v \n", b, b)
}
代码输出:
变量a的类型为main.zhengxing,值为1
变量b的类型为main.zifuchuanliebiao,值为[c d e]
代码解析
如上代码,a的类型为main.zhengxing,其中main为packge main包,zhengxing是我们用type自定义的类型。
type类型还有很多很重要的用法,比如定义结构体,定义接口等等,我们会再后面的章节逐一介绍。