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

标签 go struct

我在 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 变得困难。我知道这可以通过其他编程语言中的继承来解决,但是 我可以在 Go 中解决这个问题吗?

最佳答案

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

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

关于go - 在 golang 的另一个结构中重用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53528573/

相关文章:

node.js - Golang 中的 nodejs setTimeout 等价物是什么?

struct - 访问枚举内的结构

c - 为什么我可以分配一个局部变量并对其进行读取,但如果我尝试在结构中分配一个指针并读取它,则会出现段错误?

c - 如何设置结构体数组的 "end"

loops - 如何填充 map

go - 如何通过另一个值的 reflect.Type 在 Golang 中转换值类型

go - 使用 Go Lang 创建用户和组。但是 Go Binary 必须只为特定用户执行

http - 如何与http.Client建立长连接?

c++ - 这个结构是如何被引用的?什么是冒号(:) at the bottom?

function - 在函数参数中传递接口(interface)指针