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

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

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题