type Employee struct { name string salary int currency string }
/* displaySalary() method has Employee as the receiver type */ func(e Employee) displaySalary() { fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary) }
type Employee struct { name string salary int currency string }
/* displaySalary() method converted to function with Employee as parameter */ funcdisplaySalary(e Employee) { fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary) }
type Human struct { name string age int phone string } type Student struct { Human //匿名字段 school string } type Employee struct { Human //匿名字段 company string }
func(h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) } funcmain() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() }
运行结果:
1 2
Hi, I am Mark you can call me on 222-222-YYYY Hi, I am Sam you can call me on 111-888-XXXX
type Human struct { name string age int phone string } type Student struct { Human //匿名字段 school string } type Employee struct { Human //匿名字段 company string }
//Human定义method func(h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone) }
//Employee的method重写Human的method 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) //Yes you can split into 2 lines here. } funcmain() { mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} sam := Employee{Human{"Sam", 45, "111-888-XXXX"}, "Golang Inc"} mark.SayHi() sam.SayHi() }
运行结果:
1 2
Hi, I am Mark you can call me on 222-222-YYYY Hi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX