1
2
3
4
| type Talker interface {
//接口里的方法
talk(data interface{}) error
}
|
1
2
3
4
5
6
7
8
| type Who struct {
name string
}
Who结构体实现了talkr接口的方法
func (t *Who) talk(word interface{}) error {
fmt.Println(t.name,":",word)
return nil
}
|
1
2
3
4
5
6
7
8
9
10
11
12
| func main() {
//声明结构体
w :=&Who{name:"people"}
dog :=&Who{name:"dog"}
// 声明接口
var talker Talker
//由于who类型实现了接口中的所有方法,所以可以Who类型赋值给接口
talker = w
_ = talker.talk("i'm person") //people : i'm person
talker = dog
_ = talker.talk("wang wang wang ")//dog : wang wang wang
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| //定义一个Earth类型
type Earth struct {
river string
}
//实现接口中的talk方法
func (e *Earth) talk(word interface{}) error {
fmt.Println(e.river,":",word)
return nil
}
//然后就可以调用啦
func main() {
//Who和Earth 是两个不同的类型,但他们都实现了相同的接口
w :=&Who{name:"people"}
e :=&Earth{river:"changjiang"}
//w.talk("dadas")
var talker Talker
talker = w
_ = talker.talk("i'm person")
talker = e
fmt.Println(e.talk("i'm very long")) //changjiang : i'm very long
}
|