加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang 继承

发布时间:2020-12-16 09:40:07 所属栏目:大数据 来源:网络整理
导读:package mainimport "fmt"type Base struct { Name string}func (b *Base) SetName(name string) { b.Name = name}func (b *Base) GetName() string { return b.Name}// 组合,实现继承type Child struct { base Base // 这里保存的是Base类型}// 重写GetNam
package main

import "fmt"

type Base struct {
    Name string
}

func (b *Base) SetName(name string) {
    b.Name = name
}

func (b *Base) GetName() string {
    return b.Name
}

// 组合,实现继承
type Child struct {
    base Base // 这里保存的是Base类型
}

// 重写GetName方法
func (c *Child) GetName() string {
    c.base.SetName("modify...")
    return c.base.GetName()
}

// 实现继承,但需要外部提供一个Base的实例
type Child2 struct {
    base *Base // 这里是指针
}

//
type Child3 struct {
    Base
}

type Child4 struct {
    *Base
}

func main() {
    c := new(Child)
    c.base.SetName("world")
    fmt.Println(c.GetName())

    c2 := new(Child2)
    c2.base = new(Base) // 因为Child2里面的Base是指针类型,所以必须提供一个Base的实例
    c2.base.SetName("ccc")
    fmt.Println(c2.base.GetName())

    c3 := new(Child3)
    c3.SetName("1111")
    fmt.Println(c3.GetName())

    c4 := new(Child4)
    c4.Base = new(Base)
    c4.SetName("2222")
    fmt.Println(c4.GetName())
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读