doutang6130 2019-03-28 16:43
浏览 8

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

In the below code:

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
", p.name, p.city)
}

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

Person is structurally typed with People, because it implemented behavior of People

For the below code:

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()
}

Why obj1.getDetails() is getting resolved? Is it because, Speaker type has embedded Person type and Person type is structurally typed with People interface type?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 目详情-五一模拟赛详情页
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line