golang 之 struct
來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。package mainimport "fmt"type gameObject struct {name stringtest}type test struct {v string}func (o *test) Val() {fmt.Printf("test %s \n", o.v)}func (o *test) Attack() {fmt.Printf("test Attack %s \n", o.v)}func (o *gameObject) Name() string {return o.name}func (o *gameObject) Attack() {fmt.Printf("GameObject %s do not know how to attack\n", o.name)}type player struct {gameObject}func (p *player) Attack() {fmt.Printf("player %s attacks\n", p.name)}type monster struct {gameObject}type challenger interface {Name() stringAttack()}func main() {p := &player{gameObject: gameObject{name: "devgl", test: test{v: "xxx"}}}m := &monster{gameObject: gameObject{name: "slime", test: test{v: "xxx2"}}}Attack(p)Attack(m)m.Attack()m.Val()m.gameObject.test.Val()m.gameObject.test.Attack()}func Attack(c challenger) {c.Attack()}代碼運行結果:player devgl attacksGameObject slime do not know how to attackGameObject slime do not know how to attacktest xxx2 test xxx2 test Attack xxx2 用struct來聲明一個結構體總結:對於多層嵌套得 struct:內層struct屬性會“嵌入”(embed,繼承)到外層;外層struct屬性會覆蓋內層struct的相同屬性;struct之間有層級關係; 207 次點擊