gpt4 book ai didi

go - 我可以在共享结构中允许任意字段吗?

转载 作者:行者123 更新时间:2023-12-01 22:43:24 25 4
gpt4 key购买 nike

我想在共享库中定义一个对象,

type Common struct {
field_a string
custom interface{}
}

在哪里 custom预计将包含此公共(public)对象的用户可能在其文件中定义的其他字段,例如,
// module-1
type Mod1Customs struct {
abc string
}

从这里,我希望能够设置 Common.customMod1Customs这样我就可以同时访问 field_aabc在 module-1 中以同样的方式。我想对可能定义完全不同的结构以分配给 custom 的其他模块做同样的事情尽管。

一般的想法是创建一个具有预定义默认值的对象,并允许对象用户添加自己的自定义字段。

这可能吗?

最佳答案

您似乎正在寻找的是嵌入:

type Common struct {
FieldA string
}

type Mod1Customs struct {
Common
Abc string
}

然后 Mod1Customs 直接访问所有 Common 字段:
c := Mod1Customs{}
fmt.Println(c.FieldA)
fmt.Println(c.Abc)

Embedding在 Effective Go 中了解更多详情。

如果您有一些处理公共(public)字段的函数(无论是什么结构),那么您将使用 interface 来实现它。声明您需要的字段。 Mod1Customs将自动符合该接口(interface)。

关于go - 我可以在共享结构中允许任意字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60381083/

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