-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_interface.go
92 lines (81 loc) · 1.47 KB
/
4_interface.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* @Author: your name
* @Date: 2021-01-05 14:01:20
* @LastEditTime: 2021-01-06 17:56:27
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /demo/4_interface.go
*/
package main
import "fmt"
type Irun interface {
run()
}
type Italk interface {
talk()
}
type people struct {
Name string
}
// 接口继承
type animal interface {
Irun
Italk
}
type any = interface{}
type mnt = int
func (p *people) run() {
fmt.Printf("p.Name: %s会跑\n", p.Name)
}
func (p people) talk() {
fmt.Printf("p.Name: %s会叫\n", p.Name)
}
func sun(a any) {
if b, ok := a.(bool); ok {
fmt.Printf("b: %v\n", b)
}
if b, ok := a.(string); ok {
fmt.Printf("b: %v\n", b)
}
if b, ok := a.(mnt); ok {
fmt.Printf("b: %v\n", b)
}
if b, ok := a.(student); ok {
fmt.Printf("b: %v\n", b)
}
}
func initcf() {
var person people = people{
"李青",
}
var (
p1 Irun
p2 Italk
p3 animal
)
// people同时实现了两个接口
p1 = &person
p2 = person // 结构体和指针都行
p3 = &person
fmt.Printf("p1: %v\n", p1)
fmt.Printf("p2: %v\n", p2)
fmt.Printf("p3: %v\n", p3)
// any类型的作用
// 1. 传参数可以是任意类型
const bl = true
sun(bl)
sun("你好")
sun(12)
sun(student{Name: "jack"})
// 值是任意类型的字典
var mp map[string]any
mp = make(map[string]any)
mp["name"] = "jack"
mp["age"] = 32
mp["isMoney"] = true
fmt.Printf("mp: %v\n", mp)
age, ok := mp["age"]
if ok {
fmt.Printf("age: %v\n", age)
}
}