type定义简单类型
语法
type关键字 类型名 type
type myint int
type mystring string
func main() {
var i1 myint = 1
i2 := 1
fmt.Printf("类型比较:\ti1的类型:%T\ti2的类型:%T\n", i1, i2)
var s1 mystring = "hello"
s2 := "hello"
fmt.Printf("类型比较:\ts1的类型:%T\ts2的类型:%T\n", s1, s2)
}

此时的i1 i2;s1 s2的类型是不一样的,不可以将i1 i2或s1 s2相互赋值 。
类型别名
语法
type关键字 类型别名 = type
type myint = int
func main() {
var i1 myint = 1
i2 := 1
fmt.Printf("类型比较:\ti1的类型:%T\ti2的类型:%T\n", i1, i2)
fmt.Println(i1 + i2)
}

type定义函数类型
type myfun func(int, int) string
func fun1() myfun {
fun := func(a, b int) string {
s := strconv.Itoa(a) + strconv.Itoa(b)
return s
}
return fun
}
func main() {
testfun := fun1()
fmt.Println(testfun(100, 200))
}
本文介绍了Go语言中type关键字用于定义简单类型如int和string,类型别名的应用,以及如何定义和使用函数类型。通过实例展示了不同类型之间的比较和操作。

3万+

被折叠的 条评论
为什么被折叠?



