使用嵌入式类型的结构化类型-GO

时间:2019-03-28 16:43:13

标签: go structural-typing

在下面的代码中:

package main

import "fmt"

type People interface {
    sayHello()
    getDetails()
}

type Person struct {
    name        string
    age         int
    city, phone string
}

// A person method
func (p Person) sayhello() {
    fmt.Printf("Hi, I am %s, form %s\n", p.name, p.city)
}

// A person method
func (p Person) getDetails() {
    fmt.Printf("[Name: %s, Age: %d, City: %s, Phone: %s]\n", p.name, p.age, p.city, p.phone)
}

PersonPeoplestructurally typed,因为它实现了People

的行为

对于以下代码:

type Speaker struct {
    Person     // type embedding for composition
    speaksOn   []string
    pastEvents []string
}

func main() {
    obj1 := Speaker{Person{"aa", 23, "ww", "234"}, []string{"aa", "bb"}, []string{"dd", "ee"}}
    obj2 := Speaker{Person{"aa", 23, "ww", "234"}, []string{"aa", "bb"}, []string{"dd", "ee"}}
    obj3 := Speaker{Person{"aa", 23, "ww", "234"}, []string{"aa", "bb"}, []string{"dd", "ee"}}
    peopleList := [...]People{obj1, obj2, obj3}
    obj1.getDetails() 
    obj1.sayhello()
}

为什么obj1.getDetails()得到解决?是因为Speaker类型嵌入了Person类型,并且Person类型在结构上使用People接口类型进行了类型化?

0 个答案:

没有答案