在下面的代码中:
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)
}
Person
与People
是structurally 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
接口类型进行了类型化?