[英]Nested string fields can not be updated using reflection in an arbitrary Go struct
[英]Can I allow arbitrary fields in a shared struct?
我想在共享库中定义一个对象,
type Common struct {
field_a string
custom interface{}
}
期望custom
包含此公共对象的用户可能在其文件中定义的其他字段,例如,
// module-1
type Mod1Customs struct {
abc string
}
从这里开始,我希望能够将Common.custom
设置为Mod1Customs
以便我可以从模块 1 中以相同的方式访问field_a
和abc
。 我想为其他模块做同样的事情,这些模块可能定义了一个完全不同的结构来分配给custom
。
总体思路是创建一个具有预定义默认值的对象,并允许对象用户添加自己的自定义字段。
这可能吗?
您似乎正在寻找的是嵌入:
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
来实现它,该interface
声明您需要的字段。 Mod1Customs
将自动符合该接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.