1 package main
2
3 import "fmt"
4
5 // 空接口
6 type A interface{}
7
8 type Cat struct {
9 color string
10 }
11
12 type Person struct {
13 name string
14 age int
15 }
16
17 // 接口A是空接口,理解为代表了任意类型
18 func test1(a A) {
19 fmt.Println(a)
20 }
21
22 func test2(a interface{}) {
23 fmt.Println("--->", a)
24 }
25
26 func test3(slice2 []interface{}) {
27 for i := 0; i < len(slice2); i++ {
28 fmt.Printf("第%d个数据:%v\n", i+1, slice2[i])
29 }
30 }
31
32 func main() {
33 /*
34 空接口(interface{})
35 不包含任何的方法,正因为如此,所有的类型都实现了空接口,因此空接口可以存储任意类型的数值。
36
37 fmt包下的Print系列函数:
38 func Print(a ...interface{}) (n int, err error)
39 func Printf(format string, a ...interface{}) (n int, err error)
40 func Println(a ...interface{}) (n int, err error)
41 */
42
43 var a1 A = Cat{"花猫"}
44 var a2 A = Person{"王二狗", 30}
45 var a3 A = "haha"
46 var a4 A = 100
47 fmt.Println(a1) // {花猫}
48 fmt.Println(a2) // {王二狗 30}
49 fmt.Println(a3) // haha
50 fmt.Println(a4) // 100
51
52 test1(a1) // {花猫}
53 test1(a2) // {王二狗 30}
54 test1(3.14) // 3.14
55 test1("Ruby") // Ruby
56
57 test2(a3) // ---> haha
58 test2(1000) // ---> 1000
59
60 // map,key字符串,value任意类型
61 map1 := make(map[string]interface{})
62 map1["name"] = "李小花"
63 map1["age"] = 30
64 map1["friend"] = Person{"Jerry", 18}
65 fmt.Println(map1) // map[age:30 friend:{Jerry 18} name:李小花]
66
67 // 切片,存储任意类型的数据
68 slice1 := make([]interface{}, 0, 10)
69 slice1 = append(slice1, a1, a2, a3, a4, 100, "abc")
70 fmt.Println(slice1) // [{花猫} {王二狗 30} haha 100 100 abc]
71 test3(slice1)
72
73 }