接口的继承实现的和定义

 1 package main
 2 
 3 import "fmt"
 4 
 5 type Humaner01 interface {
 6     sayHi()
 7 }
 8 
 9 type Personer interface {
10     Humaner01 //匿名字段,继承sayHi()
11     sing(lrc string)
12 }
13 
14 type Student10 struct {
15     name string
16     id  int
17 }
18 
19 func (temp *Student10) sayHi(){
20    fmt.Printf("Student10[%s,%d] sayHi
",temp.name,temp.id)
21 }
22 
23 func (temp *Student10)sing(lrc string)  {
24    fmt.Println("student10在唱:",lrc)
25 }
26 
27 func main(){
28     //定义一个接口类型的变量
29     var i Personer
30     s := &Student10{"mike",7777}
31     i = s
32     i.sayHi()
33     i.sing("人民解放歌")
34 
35     var h Humaner01
36     h = s
37     h.sayHi()
38 
39     h = i //子接口可以赋值给父接口
40     h.sayHi()
41 
42     //i = h //父接口定义变量不能给子接口
43 
44 }
 1 package main
 2 
 3 import "fmt"
 4 
 5 //定义一个接口类型
 6 type Humaner interface {
 7      //方法,只有声明,没有实现,由别的类型(自定义类型)实现
 8      sayHi()
 9 }
10 
11 type Student9 struct {
12     name string
13     id  int
14 }
15 
16 func (temp *Student9) sayHi(){
17      fmt.Printf("Student9[%s,%d] sayHi
",temp.name,temp.id)
18 }
19 
20 type Teacher struct {
21      addr string
22      id  int
23 }
24 
25 func (temp *Teacher) sayHi()  {
26     fmt.Printf("Teacher[%s,%d] sayHi
",temp.addr,temp.id)
27 }
28 
29 type Worker4 struct {
30    id int
31 }
32 
33 func (temp *Worker4) sayHi()  {
34     fmt.Printf("Worker4[%d] sayHi
",temp.id)
35 }
36 
37 //定义一个普通函数,函数的参数为接口类型
38 //只有一个函数,可以表现有不同的形式,多态
39 func WhoSayHi(i Humaner){ //接口作为参数
40     i.sayHi()
41 }
42 
43 
44 func main()  {
45 
46     //定义一个接口的类型
47     //var i Humaner
48    // 只有实现了此接口的方法的类型,那个这个类型的变量才能赋值给接口变量
49     s := &Student9{"mike",7777}
50 
51     //i =s
52     //i.sayHi()
53 
54     t := &Teacher{"bj",9999}
55     //i = t
56 
57     //i.sayHi()
58 
59     w := &Worker4{8888}
60     //i= w
61     //i.sayHi()
62 
63     WhoSayHi(s)
64     WhoSayHi(t)
65     WhoSayHi(w)
66 
67     //创建一个切片,切片放入是接口
68      x := make([]Humaner,3)
69      x[0] = s
70      x[1]= t
71      x[2] = w
72 
73      for _,i :=range x{
74          i.sayHi()
75      }
76 
77 
78 
79 }
原文地址:https://www.cnblogs.com/dqh123/p/12073242.html