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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| package main
import ( "fmt" )
type Human struct { name string age int phone string } type Student struct { Human school string loan float32 } type Employee struct { Human company string money float32 }
func (h Human) SayHi() { fmt.Printf("Hi, I am %s, you can call me on %s\n", h.name, h.phone) }
func (h Human) Sing(lyrics string) { fmt.Println("La la la...", lyrics) }
func (h Human) Guzzle(beerStein string) { fmt.Println("Guzzle Guzzle Guzzle...", beerStein) }
func (e Employee) SayHi() { fmt.Printf("Hi I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) }
func (s Student) BorrowMoney(amount float32) { s.loan += amount }
func (e Employee) SpendSalary(amount float32) { e.money -= amount }
type Men interface { SayHi() Sing(lyrice string) Guzzle(beerStein string) }
type YoungChap interface { SayHi() Sing(song string) BorrowMoney(amount float32) }
type ElderlyGent interface { SayHi() Sing(song string) SpendSalary(amount float32) }
func main() { lucy := Student{Human{"lucy", 19, "10086"}, "tsinghua", 100.00} lily := Student{Human{"lily", 19, "10086"}, "tsinghua", 100.00} liming := Student{Human{"liming", 19, "10086"}, "tsinghua", 100.00} tom := Employee{Human{"tom", 29, "10000"}, "Google", 200.00} var i Men i = lucy fmt.Println("This is lucy, a student:") i.SayHi() i.Sing("Happy Birthday") i.Guzzle("Ha ha ha...")
i = tom fmt.Println("This is tom, an Employee:") i.SayHi()
fmt.Println("Let's use a slice of Men and see what happens:") x := make([]Men, 3) x[0], x[1], x[2] = lucy, lily, liming for _, value := range x { value.SayHi() } }
|