首页 > 解决方案 > 如何组合 2 个结构内容,一个具有相同的键

问题描述

我有两个结构,一个具有比另一个更多的键,具有更少的键和更多的相同。我想一次给多个键结构提供更少的内容,怎么做?

type moreStruct struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"`
    D string `json:"d"`
    E string `json:"e"`
}

type leseStruct struct {
    A string `json:"a"`
    B string `json:"b"`
    D string `json:"d"`
}

more := moreStruct{
        A: "aaa",
        B: "bbb",
        C: "ccc",
        D: "ddd",
        E: "eee",
}
less := leseStruct{
        A: "aaaaaaa",
        B: "bbbbbbb",
        D: "ddddddd",
}

//hava any better mothod than below in one line
more.A = less.A
more.B = less.B
more.D = less.D

标签: gostruct

解决方案


是的,因此,如果您可以更改类型/结构本身,则可以使用嵌入,以便重新分配整个字段子集。这确实意味着您必须稍微更改编写文字的方式,并且由于您使用的是 json,因此需要导出嵌入式类型。

// Less, the smallest subset of fields that are shared
type Less struct {
    A string `json:"a"`
    B string `json:"b"`
    D string `json:"d"`
}

// More the type that has all the fields in Less + some of its own
type More struct {
    Less // embed Less in this type
    C string `json:"c"`
    E string `json:"e"`
}

现在我们已经有了这些类型,这就是您在文字中初始化字段的方式:

more := More{
    Less: Less{
        A: "aaa",
        B: "bbb",
        D: "ddd",
    },
    C: "ccc",
    E: "eee",
}
// or the dirty way (no field names) - don't do this... it's nasty
yuck := More{
    Less{
        "a",
        "b",
        "d",
    },
    "c",
    "e",
}

现在,假设我们有一个less像这样的变量:

less := Less{
    A: "aaaaa",
    B: "bbbbb",
    D: "ddddd",
}

现在我们要将这些值复制到more我们在上面创建的变量中:

more.Less = less

工作完成...因为Less类型是嵌入的,所以 json 编组和解组仍然会以相同的方式工作

演示


推荐阅读