Golang learning 結(jié)構(gòu)體 struct 與面向?qū)ο?/h2>

Go 語言并不是傳統(tǒng)意義上的面向?qū)ο笳Z言,但是實現(xiàn)很小的面向?qū)ο蟮臋C制。
匿名嵌入并不是繼承,無法實現(xiàn)多態(tài)處理,雖然配合方法集,可用接口來實現(xiàn)一些類似操作,但是其本質(zhì)是完全不同的。

type Animal struct {          聲明Animal
    name string
    age  int
}
type Cat struct {

    Animal                       匿名字段
    teeth string  "牙"         "牙" 不是注釋,字段標簽(tag)不是注釋,是用來描述字段的元數(shù)據(jù),是struct的一部分
    leg  int
}
type Animal struct {                        聲明Animal類
    name string
    age  int
}
type AnimalAction interface {        聲明AnimalAction  接口類

    eat()                                        聲明func
    voice()                                     聲明func

}
func (a Animal) eat(){                  Animal實現(xiàn)接口AnimalAction    方法eat()

    fmt.Print("eat")
}
func (a Animal) voice(){                 Animal實現(xiàn)接口AnimalAction    方法voice()

    fmt.Print("voice")
}




type Cat struct {                         聲明Cat類  
    Animal                                匿名字段Animal     嵌入類型
    teeth string "牙"
    leg  int
}

type NewAction interface {     聲明NewAction  接口類
    run()
        sing(s func(name string))   聲明閉包sing
}

func (c Cat) eat(){                    Cat實現(xiàn) func eat(),類似繼承的重寫,但不是重寫。 
    c.Animal.eat()                    Cat調(diào)用Animal func eat(),類似super.eat()  但不是調(diào)用父類方法
    fmt.Print("cat eat")

}
func (c Cat) run(){                    Cat實現(xiàn)NewAction func run()

    fmt.Print("cat run")

}
func (c Cat) sing(s func(name string)){       實現(xiàn)閉包sing
    s("cat")
}

func test(){


   a := Animal{
    "a",
    12,

   }
   a.eat()
   a.voice()

   c := Cat{
    Animal{
        "cat",
        1,
    },
    "尖牙",
    4,
   }

   c.eat()
   c.voice()
   c.run()

   c.sing(func(name string) {         調(diào)用閉包

      fmt.Print("\n" + name + "sing")
   })


}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容