接口
type Humaner interface {
hello()
}
type Student struct {
name string
id int
}
func (tmp *Student) hello() {
fmt.Println(tmp.name, tmp.id)
}
func main() {
f := Student{"panghu", 1}
f.hello()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
空接口
func main() {
var i interface{} = 1
fmt.Println("i = ", i)
i = "abc"
fmt.Println("i = ", i)
}
1
2
3
4
5
6
7
8
9
接口继承
type Humaner interface {
hello()
}
type Personer interface {
Humaner
sing(lrc string)
}
type Student struct {
name string
id int
}
func (tmp *Student) hello() {
fmt.Println(tmp.name, tmp.id)
}
func (tmp *Student) sing(lrc string) {
fmt.Println("Student在唱着:", lrc)
}
func main() {
s := Student{"panghu", 1}
s.hello()
s.sing("hello golang")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
接口转换
type Humaner interface {
hello()
}
type Personer interface {
Humaner
sing(lrc string)
}
type Student struct {
name string
id int
}
func (tmp *Student) hello() {
fmt.Println(tmp.name, tmp.id)
}
func (tmp *Student) sing(lrc string) {
fmt.Println("Student在唱着:", lrc)
}
func main() {
var iPro Personer
iPro = &Student{"panghu", 18}
iPro.hello()
var i Humaner
i = iPro
i.hello()
}
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
类型断言
type Student struct {
name string
id int
}
func main() {
i := make([]interface{}, 3)
i[0] = 1
i[1] = "hello go"
i[2] = Student{"mike", 666}
for _, v := range i {
if value, ok := v.(int); ok == true {
fmt.Println(value, ok)
} else if value, ok := v.(string); ok == true {
fmt.Println(value, ok)
} else if value, ok := v.(Student); ok == true {
fmt.Println(value, ok)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
switch断言
type Student struct {
name string
id int
}
func main() {
i := make([]interface{}, 3)
i[0] = 1
i[1] = "hello go"
i[2] = Student{"mike", 666}
for index, data := range i {
switch value := data.(type) {
case int:
fmt.Printf("x[%d]类型为int, 内容为%d\n", index, value)
case string:
fmt.Printf("x[%d]类型为string, 内容为%s\n", index, value)
case Student:
fmt.Printf("x[%d]类型为Student, 内容为%s\n", index, value)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21