我想在共享库中定义一个对象,type Common struct { field_a string custom interface{}}wherecustom应保存此公共对象的用户可能在其文件中定义的其他字段,例如,// module-1type Mod1Customs struct { abc string}从这里开始,我希望能够设置Common.custom为,Mod1Customs以便我可以从 module-1 中以相同的方式field_a访问两者。abc我想为其他模块做同样的事情,这些模块可能定义一个完全不同的结构来分配custom。一般的想法是创建一个具有预定义默认值的对象,并允许对象用户添加自己的自定义字段。这可能吗?
1 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
您似乎正在寻找的是嵌入:
type Common struct {
FieldA string
}
type Mod1Customs struct {
Common
Abc string
}
然后 Mod1Customs 直接访问所有 Common 字段:
c := Mod1Customs{}
fmt.Println(c.FieldA)
fmt.Println(c.Abc)
有关更多详细信息,请参阅嵌入Effective Go。
如果您有一些处理公共字段的函数(无论是什么结构),那么您将使用interface声明您需要的字段的 an 来实现它。Mod1Customs将自动符合该接口。
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报
0/150
提交
取消