go类型定义与类型别名区别

类型定义

语法格式

// 单个定义
type NewTypeName SourceType

// 多个定义
type (
    NewTypeName1 sourceType1
    NewTypeName2 sourceType2
)

注意事项

一个新定义的类型与它的源类型为两个不同的类型
// 自定义类型
type myInt int

func typName() {
	fmt.Printf("myInt = %v, int = %v\n", reflect.TypeOf(myInt(1)), reflect.TypeOf(int(1)))
	// output:
	// myInt = main.myInt, int = int
}
一个新定义的类型和它源类型得底层类型一致,并且他们的值可以显示转换
// 自定义类型
type myInt int

func typTransfer() {
	var a int
	var b myInt
	a = 1
	b = myInt(a)
	fmt.Printf("a = %d, b = %d\n", a, b)
	// output:
	// a = 1, b = 1
}
类型的定义可以出现在函数体类
func typeFun() {
	type funInt int
	var c funInt = 1

	fmt.Printf("c = %d, c type is %v\n", c, reflect.TypeOf(c))
	// output:
	// c = 1, c type is main.funInt
}

类型别名

语法格式

type (
    Name = string
    Age = int
)

type table = map[string]int
type Table = map[Name]Age

注意事项

类型别名与源类型是同一种类型
// 类型别名
type myStr = string

func aliasType() {
	var s myStr
	var ts string

	fmt.Printf("s type is %v, ts type is %v\n", reflect.TypeOf(s), reflect.TypeOf(ts))
	// output:
	// s type is string, ts type is string
}
posted @   dxx99  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示