interface
Posted chenguifeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了interface相关的知识,希望对你有一定的参考价值。
1 package main 2 3 import "fmt" 4 5 type Human struct { 6 name string 7 age int 8 phone string 9 } 10 11 type Student struct { 12 Human //匿名字段 13 school string 14 loan float32 15 } 16 17 type Employee struct { 18 Human //匿名字段 19 company string 20 money float32 21 } 22 23 //Human实现SayHi方法 24 func (h Human) SayHi() { 25 fmt.Printf("Hi, I am %s you can call me on %s ", h.name, h.phone) 26 } 27 28 //Human实现Sing方法 29 func (h Human) Sing(lyrics string) { 30 fmt.Println("La la la la...", lyrics) 31 } 32 33 //Employee重载Human的SayHi方法 34 func (e Employee) SayHi() { 35 fmt.Printf("Hi, I am %s, I work at %s. Call me on %s ", e.name, 36 e.company, e.phone) 37 } 38 39 // Interface Men被Human,Student和Employee实现 40 // 因为这三个类型都实现了这两个方法 41 type Men interface { 42 SayHi() 43 Sing(lyrics string) 44 } 45 46 func main() { 47 mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00} 48 paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100} 49 sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000} 50 tom := Employee{Human{"Tom", 37, "222-444-XXX"}, "Things Ltd.", 5000} 51 52 //定义Men类型的变量i 53 var i Men 54 55 //i能存储Student 56 i = mike 57 fmt.Println("This is Mike, a Student:") 58 i.SayHi() 59 i.Sing("November rain") 60 61 //i也能存储Employee 62 i = tom 63 fmt.Println("This is tom, an Employee:") 64 i.SayHi() 65 i.Sing("Born to be wild") 66 67 //定义了slice Men 68 fmt.Println("Let‘s use a slice of Men and see what happens") 69 x := make([]Men, 3) 70 //这三个都是不同类型的元素,但是他们实现了interface同一个接口 71 x[0], x[1], x[2] = paul, sam, mike 72 73 for _, value := range x { 74 value.SayHi() 75 } 76 }
以上是关于interface的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot 提示:java.lang.IllegalStateException: No primary or default constructor found for interface