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
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通