gpt4 book ai didi

go - 如何修改未知类型的结构中的字段?

转载 作者:IT王子 更新时间:2023-10-29 02:36:46 27 4
gpt4 key购买 nike

我有多个具有一个公共(public)字段的结构;我们在这里称它为 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 因为它保存了每个结构的创建时间,我想跟踪结构的历史,所以我会知道它是否变化。将创建时间放在结构中会搞砸,因为每次生成新结构时创建时间都会不同,即使其实际数据可能相同。

最佳答案

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

// 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 , 但使用接口(interface)通常更具可读性。

关于go - 如何修改未知类型的结构中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com