38_方法的重写

package main
 
import "fmt"
 
type Person struct {
	//和变量定义不同,不要写var关键字
	Id   int
	Name string
	Sex  byte
}
type Student struct {
	Person
	Hobby string
}
 
//改变接收者类型,可以实现方法重写
func (s Person) PrintValue() {
	fmt.Println("该方法receiver is person")
 
}
func (s Student) PrintValue() {
	fmt.Println("该方法receiver is student")
 
}
 
func main() {
	s1 := Student{Person{1, "steven", 'm'}, "running"}
	s1.PrintValue()        //就近原则
	s1.Person.PrintValue() //显示的调用上一层
 
}

猜你喜欢

转载自www.cnblogs.com/zhaopp/p/11565408.html