/**
* 什么是method(方法)?method是函數(shù)的另外一種形態(tài),隸屬于某個類型的方法。
* method的語法:func (r Receiver) funcName (parameters) (result)。
* receiver可以看作是method的第一個參數(shù),method并且支持繼承和重寫。
*/
package main
import (
"fmt"
)
type Human struct {
name string
age int
}
// 字段繼承
type Student struct {
Human // 匿名字段
school string
}
type Employee struct {
Human // 匿名字段
company string
}
// 函數(shù)的另外一種形態(tài):method,語法:func (r Receiver) funcName (parameters) (result)
// method當作struct的字段使用
// receiver可以看作是method的第一個參數(shù)
// 指針作為receiver(接收者)和普通類型作為receiver(接收者)的區(qū)別是指針會對實例對象的內容發(fā)生操作,
// 普通類型只是對副本進行操作
// method也可以繼承,下面是一個匿名字段實現(xiàn)的method,包含這個匿名字段的struct也能調用這個method
func (h *Human) Info() {
// method里面可以訪問receiver(接收者)的字段
fmt.Printf("I am %s, %d years old\n", h.name, h.age)
}
// method重寫,重寫匿名字段的method
// 雖然method的名字一樣,但是receiver(接收者)不一樣,那么method就不一樣
func (s *Student) Info() {
fmt.Printf("I am %s, %d years old, I am a student at %s\n", s.name, s.age, s.school)
}
func (e *Employee) Info() {
fmt.Printf("I am %s, %d years old, I am a employee at %s\n", e.name, e.age, e.company)
}
func main() {
s1 := Student{Human{"Jack", 20}, "tsinghua"}
e1 := Employee{Human{"Lucy", 26}, "Google"}
// 調用method通過.訪問,就像struct訪問字段一樣
s1.Info()
e1.Info()
}