使用接口解组结构切片
我有一个非常有趣的案例,假设我们有这个结构体,
type Test struct {
Field1 string `json:"field1"`
Field2 ABC `json:"abc"`
}
type ABC interface {
Rest()
}
解组这个结构体不是问题,您只需指向实现接口的正确结构体,除非您有 []Test
是否有当其中一个字段是接口时解组结构切片的方法?
谢谢
I have a very interesting case, let's say we have this struct
type Test struct {
Field1 string `json:"field1"`
Field2 ABC `json:"abc"`
}
type ABC interface {
Rest()
}
Unmarshalling this struct is not a problem, you could just point to the right struct which implements the interface, unless you have []Test
Is there a way to unmarshall slice of structs when one of the field is interface?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要实现
Unmarshaler接口
来测试,然后在
UnmarshalJSON
函数中你需要一一检查它(示例中的第45-55行)幸运的是现在有了
通用
,这是示例:游乐场
You need to implement
Unmarshaler interface
to Test,Then in
UnmarshalJSON
func you need to check it one by one (line 45-55 in the example)Luckily there is now
generic
, this is the example :playground
使用以下代码将接口字段解组为特定的具体类型。有关更多详细信息,请参阅评论:
在 Playground 上运行代码。
Use the following code to Unmarshal the interface field to a specific concrete type. See the commentary for more details:
Run the code on the playground.