1 package main
2
3 import (
4 "fmt"
5 "strconv"
6 )
7
8 // 1.定义一个新的类型
9 type myint int
10 type mystr string
11
12 // 2.定义函数类型
13 type myfun func(int, int) string
14
15 func fun1() myfun { //fun1()函数的返回值是myfun类型
16 fun := func(a, b int) string {
17 s := strconv.Itoa(a) + strconv.Itoa(b)
18 return s
19 }
20 return fun
21 }
22
23 // 3.类型别名
24 type myint2 = int //不是重新定义新的数据类型,只是给int起别名,和int可以通用
25
26 func main() {
27 /*
28 type:用于类型定义和类型别名
29
30 1.类型定义:type 类型名 Type
31 2.类型别名:type 类型名 = Type
32 */
33
34 var i1 myint
35 var i2 = 100 // int
36 i1 = 200
37 fmt.Println(i1, i2) // 200 100
38
39 var name mystr
40 name = "王二狗"
41 var s1 string
42 s1 = "李小花"
43 fmt.Println(name, s1) // 王二狗 李小花
44 //i1 = i2 //cannot use i2 (type int) as type myint in assignment
45 //name = s1 //cannot use s1 (type string) as type mystr in assignment
46 fmt.Printf("%T,%T,%T,%T\n", i1, i2, name, s1) // main.myint,int,main.mystr,string
47 fmt.Println("----------------------------------")
48
49 res1 := fun1()
50 fmt.Println(res1(10, 20)) // 1020
51 fmt.Println("----------------------------------")
52
53 var i3 myint2
54 i3 = 1000
55 fmt.Println(i3) // 1000
56 i3 = i2 // 类型别名可以这么操作
57 fmt.Println(i3) // 100
58 fmt.Printf("%T,%T,%T\n", i1, i2, i3) // main.myint,int,int
59
60 }