Golang 接口

2020-10-21  本文已影响0人  邦_

package main

import "fmt"

type Person struct {
    name string
    age  int
    sex  string
}

type Worker struct {
    Person
    number int
}

func (p Person) eat() {

    fmt.Printf("%s在吃饭....", p.name)

}




func (w Worker) eat()  {
    fmt.Printf("%s子类在吃饭....",w.name)
}


func (w Worker) work() {
    fmt.Printf("%s在工作....\n", w.name)
}
func (w *Worker) sleep() {
    w.name = "小白"
    fmt.Printf("%s在睡觉....\n", w.name)

}

func main() {

    var worker Worker
    worker.name = "张三"
    worker.work()
    worker.eat()
    //go的官方文档中说到,不支持重载机制可以简化方法调度。从其他语言的经验上看,重载只是偶尔有用,但会在实践中引起误解和导致脆弱性。
    worker1 := &Worker{Person:Person{name: "李四"} }
    worker1.sleep()
    worker1.eat()
    fmt.Println(worker1.name)

}

上一篇下一篇

猜你喜欢

热点阅读