go语言之面向对象

    技术2024-03-25  81

    "——————人与人之间还是简单点好————————"

    handler1.go // 这个文件处理几几的事情 package handler1 //定义了一个接口函数 type FatherAction interface { ToEat() Work() Sleep() bool } //定义了一个继承的结构类型(此方法又叫 匿名组合) type Father struct { FatherAction //继承接口函数 成员函数 sing string study string } func(f *Father)GoHome{//... } jkwan.go // 这个文件做自己的事,还要做Father的事 package money import ( "encoding/json" "fmt" "time" "xxx/handler1" "xxx/util" ) type Money struct { util.MsgHeader //匿名组合 Params Params `json:"params"` } type Params struct { Operate string `json:"operate"` }

    实例调用接口函数:

    主要是起到了继承的作用。Life 继承了 handler1.Handler 主要是方便代码复用 定义一个总结构 下发,回复 type Life struct { handler1.Father //里面是 结构体 (接口函数) 成员函数 Request Money //消息体 Response util.MsgResp //回复体 } func NewHandle(msg interface{}) *Life { var enen Life if err := json.Unmarshal(msg.([]byte), &enen.Request); err != nil { log.WithFields(log.Fields{"msg": msg}).Info("Unmarshal failed") } return &enen } //为总结构定义方法 //这些个方法,就直接实现了Father 的动作) func (p *Life) ToEat() {//... } func (p *Life) Work() {//... } func (p *Life) Sleep() bool {//... } 本质上go语言时没有继承的,go本身使用 结构组合 实现了 伪继承 !
    Processed: 0.016, SQL: 9