golang使用组合完成伪继承

import "fmt"

type A struct {
    a string
}

func NewA(aa string) *A {
    return &A{aa}
}

func (a *A) Print() {
    fmt.Printf("%T\n", a)
}

type B struct {
    *A
}

func NewB(aa string) *B {
    return &B{NewA(aa)}
}

func main() {
    b := NewB("bb")
    b.Print()
}

// go里面用组合模拟了继承, 其本质是一种语法糖, 无法实现继承中动态绑定等特性. 且构造函数, 连伪继承都达不到.
// 因此本例中, 输出是 `*main.A`

 

posted @ 2017-11-09 15:46  代码会说话  阅读(599)  评论(0编辑  收藏  举报