package main
import "fmt"
type Person struct { //爹
id int
name string
age int
}
// 定义结构体类型 (子类)
type Student struct {
Person // 匿名字段实现继承 (结构体嵌套结构体)
//p Person // 也可以为结构体Person起别名
score int
}
func main() {
p1 := Person{
id: 1,
name: "haha",
age: 10,
}
stu := Student{
score: 123,
Person: p1,
}
fmt.Printf("%+v\n", stu)
fmt.Println(stu.name)
fmt.Println(stu.age)
fmt.Println(stu.Person.name)
}
/*
{Person:{id:1 name:haha age:10} score:123}
haha
10
haha
*/
单实例绑定
package main
import (
"log"
)
type cat struct { //爹
name string
age int
}
type dog struct {
name string
aget int
}
type tomcat struct { //儿子
tomcatid int
cat
}
// 给Person结构体绑定一个BigHello
func (p cat) BigHello() {
log.Printf("[tomcat.BigHello][name:%+v]", p)
}
func main() {
c1 := cat{
name: "tom",
age: 3,
}
tc1 := tomcat{
tomcatid: 001,
cat: c1,
}
tc1.BigHello()
}
// [tomcat.BigHello][name:{name:tom age:3}]
多态灵魂承载容器
package main
import (
"log"
)
type avicii1 interface {
avicii()
}
type cat1 struct {
name string
age int
}
func (c *cat1) avicii() {
log.Printf("[单实例绑定方法][cat.ChangeAge1][p.Age:%v]", c.age)
}
type dog1 struct {
name string
age int
}
//type tomcat struct {
// tomcatid int
// cat
//}
func (d dog1) avicii() {
log.Printf("[单实例绑定方法][Person.ChangeAge2][p.Age:%v]", d.age)
}
func sendcat(n avicii1) {
n.avicii()
}
func main() {
c1 := cat1{
name: "tom",
age: 3,
}
tc1 := dog1{
name: "datou",
age: 5,
}
// 直接调用结构体绑定的方法
log.Printf("直接调用结构体绑定的方法")
c1.avicii()
tc1.avicii()
//体现多态
log.Printf("体现多态")
sendcat(&c1)
sendcat(tc1)
//灵魂
log.Printf("多态灵魂承载容器")
ns := make([]avicii1, 0)
ns = append(ns, &c1)
ns = append(ns, tc1)
for _, n := range ns {
n.avicii()
}
}
/*
2022/07/07 16:53:32 直接调用结构体绑定的方法
2022/07/07 16:53:32 [单实例绑定方法][cat.ChangeAge1][p.Age:3]
2022/07/07 16:53:32 [单实例绑定方法][Person.ChangeAge2][p.Age:5]
2022/07/07 16:53:32 体现多态
2022/07/07 16:53:32 [单实例绑定方法][cat.ChangeAge1][p.Age:3]
2022/07/07 16:53:32 [单实例绑定方法][Person.ChangeAge2][p.Age:5]
2022/07/07 16:53:32 多态灵魂承载容器
2022/07/07 16:53:32 [单实例绑定方法][cat.ChangeAge1][p.Age:3]
2022/07/07 16:53:32 [单实例绑定方法][Person.ChangeAge2][p.Age:5]
*/