type Person struct { Name string Address Address } type Address struct { Number string Street string City string State string Zip string } func (p *Person) Talk() { fmt.Println("Hi, my name is", p.Name) } func (p *Address) Location() { //fmt.Println("I'm at", p.Address.Number, p.Address.Street, p.Address.City, p.Address.State, p.Address.Zip) fmt.Println("I'm at", p.Number, p.Street, p.City, p.State, p.Zip) } func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } p.Talk() // p.Location() wrong p.Address.Location() }
上面是 一个“use-a”代码片段,不过注意“Address仍然是一个不同的对象,只不过存在于Person中”。
type Person struct { Name string Address } type Address struct { Number string Street string City string State string Zip string } func (p *Person) Talk() { fmt.Println("Hi, my name is", p.Name) } func (p *Address) Location() { //fmt.Println("I'm at", p.Address.Number, p.Address.Street, p.Address.City, p.Address.State, p.Address.Zip) fmt.Println("I'm at", p.Number, p.Street, p.City, p.State, p.Zip) } func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } p.Talk() p.Location() p.Address.Location() }上面是 一个“is-a”代码片段,不过注意“通过引入匿名域(Person)实现了is-a关系。Person是Citizen的一个匿名域(anonymous field),匿名域只给出了对象类型,而不给出类型的名字。通过匿名域,Citizen可以访问Person中的所有属性(域)和方法。”。
部分代码和文字转自《go是面向对象语言吗?》。
有疑问加站长微信联系(非本文作者)