【问题标题】:How to modify a field in a struct of an unknown type?如何修改未知类型结构中的字段?
【发布时间】:2018-09-20 03:16:28
【问题描述】:

我有多个具有一个公共字段的结构;让我们称之为common这里

type Struct1 struct {
    foo string
    bar string

    common string
}

type Struct2 struct {
    baz int
    qux string

    common string
}

我想创建一个将Interface 作为输入并取消common 的函数。可用的结构类型在编译时是未知的,所以我不能为每种类型创建单独的函数,也不能使用 switch 语句。

P.S:在我的用例中,我想取消common,因为它保存了每个结构的创建时间,并且我想跟踪结构的历史,所以我会知道它是否发生变化。将创建时间放在结构中会搞砸,因为每次生成新结构时创建时间都会不同,即使它的实际数据可能相同。

【问题讨论】:

  • 你必须使用反射。除非您有经验,否则不要这样做。最好的建议是重新设计,因为这听起来像是 XY 问题。

标签: go struct reflection interface


【解决方案1】:

定义一个带有公共字段的结构并使其实现一个接口,该接口表示它能够使公共字段无效。然后将此结构嵌入到应该能够使字段无效的其他结构类型中。

// CommonNullifier is able to nullify its common field(s)
type CommonNullifier interface {
        NullifyCommon()
}

// StructCommon contains the common struct fields
type StructCommon struct {
        Common string
}

func (sc *StructCommon) NullifyCommon() {
        sc.Common = ""
}

// Struct1 embeds common fields, thus implements CommonNullifier
type Struct1 struct {
        StructCommon
        Foo string
}

// Struct2 also embeds common fields, thus also implements CommonNullifier
type Struct2 struct {
        StructCommon
        Bar string
}

// NullifyCommon nullfies the 'common' fields in the argument
func NullifyCommon(s CommonNullifier) {
        s.NullifyCommon()
}

(在Go Playground 上查看)

您也可以使用reflection,但使用接口通常更具可读性。

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多