为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 的另一个结构中重用结构

在 golang 的另一个结构中重用结构

Go
眼眸繁星 2023-05-15 10:09:41
我在 golang 中有两个结构如下type Data struct {    Name          string    Description   string    HasMore   bool}type DataWithItems struct {    Name          string    Description   string    HasMore      bool    Items    []Items}至多DataWithItemsstruct 可以重写为 type DataWithItems struct {        Info Data        Items []Items    }但是上面的内容使得将 json 对象解码为DataWithItems. 我知道这可以通过其他编程语言的继承来解决,但是Is there a way I can solve this in Go?
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

您可以将一个结构“嵌入”到另一个结构中:


type Items string


type Data struct {

    Name        string

    Description string

    HasMore     bool

}


type DataWithItems struct {

    Data // Notice that this is just the type name

    Items []Items

}


func main() {

    d := DataWithItems{}

    d.Data.Name = "some-name"

    d.Data.Description = "some-description"

    d.Data.HasMore = true

    d.Items = []Items{"some-item-1", "some-item-2"}


    result, err := json.Marshal(d)

    if err != nil {

        panic(err)

    }


    println(string(result))

}

这打印


{"Name":"some-name","Description":"some-description","HasMore":true,"Items":["some-item-1","some-item-2"]}



查看完整回答
反对 回复 2023-05-15
?
Qyouu

TA贡献1786条经验 获得超11个赞

只需使用一个结构 - DataWithItems,有时将项目留空



查看完整回答
反对 回复 2023-05-15
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信