duanrang2627 2017-08-11 12:58
浏览 94
已采纳

Golang基本结构在子结构中定义方法

I would like to create a base struct which have to method, I want to use these methods in the substructs. For example:

type Base struct {
  Type string `json:"$type"`
}

func (b Base) GetJSON() ([]byte, error) {
  return json.Marshal(b)
}

func (b Base) SetType(typeStr string) interface{} {
  b.Type = typeStr
  return b
}

In the new struct I want to use it like this:

type Auth struct {
  Base
  Username
  Password
}

and call these methods in the main:

func main() {
  a := Auth{
    Username: "Test",
    Password: "test",
  }
  a = a.SetType("testtype").(Auth) 
  j, _ := a.GetJSON()
}

In the SetType case I got a panic caused by interface{} is not Auth type, it is Base type. In the GetJSON case I got a json about the Type, but only the Type.

Is there any solution for the problem what I want to solve?

  • 写回答

1条回答 默认 最新

  • douke6881 2017-08-11 13:27
    关注

    As mentioned in the comments, embedding is not inheritance but composition, so you'll probably have to either:

    • Re-think your design to use the tools Go has available
    • Resort to extensive hacking to get the results you want

    In the particular case you are showing (trying to get GetJSON() to include also the fields of the outer struct, here is a possible way of getting that to work that does not require many changes (just storing a pointer to the outer struct in Base when creating the struct):

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Base struct {
        Type  string      `json:"$type"`
        selfP interface{} // this will store a pointer to the actual sub struct
    }
    
    func (b *Base) SetSelfP(p interface{}) {
        b.selfP = p
    }
    
    func (b *Base) GetJSON() ([]byte, error) {
        return json.Marshal(b.selfP)
    }
    
    func (b *Base) SetType(typeStr string) {
        b.Type = typeStr
    }
    
    type Auth struct {
        Base
        Username string
        Password string
    }
    
    func main() {
        a := &Auth{
            Username: "Test",
            Password: "test",
        }
        a.SetSelfP(a) // this line does the trick
        a.SetType("testtype")
        j, _ := a.GetJSON()
        fmt.Println(string(j))
    }
    

    Playground link: https://play.golang.org/p/npuy6XMk_t

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历