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

必须:

我在golang中有两个结构,如下所示

type Data struct {
    Name          string
    Description   string
    HasMore   bool
}

type DataWithItems struct {
    Name          string
    Description   string
    HasMore      bool
    Items    []Items
}

最多DataWithItems可以将struct重写为

 type DataWithItems struct {
        Info Data
        Items []Items
    }

但是上述情况使得将json对象解码为时很难DataWithItems我知道这可以通过其他编程语言中的继承来解决,但是Is there a way I can solve this in Go?

poy:

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

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"]}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

收听以调用Golang中另一个结构使用的结构函数

结构中的指针指向另一个结构

访问另一个结构中的结构字段

另一个结构中的结构 Solidity

Golang + MongoDB嵌入式类型(在另一个结构中嵌入一个结构)

另一个文件中同一包中的golang参考结构

使用属于Golang中另一个包的结构

在golang中使用相同结构中的func引用另一个字段

在GO中从一个结构复制到另一个结构

golang结构的另一个func更改映射

Golang Map结构在另一个

Golang:另一个结构的XML属性

将结构数组嵌套到另一个结构中

将go结构嵌入gorm中的另一个结构

另一个结构中的前向声明结构的数组

我可以使用另一个结构中的结构成员吗?

如何在C#中PInvoke另一个结构内的结构数组

如何编写和读取包含C中另一个结构的结构?

从Go中的另一个嵌套结构变量访问结构的变量

转到另一个结构中的自定义结构类型

c中是否允许另一个结构内部的结构定义?

如何在另一个结构中初始化结构数组?

从另一个结构中向结构内的向量添加元素

循环创建结构并分配给IDL中的另一个结构

尝试打印封装在另一个结构中的结构的数据类型

另一个结构中结构的运算符重载会导致错误

使用另一个结构中的指定变量初始化 SwiftUI 结构

我想访问 C 中另一个结构字段内的通用结构字段

将结构声明为另一个结构中成员的正确方法