是否有一种优雅的方法来反序列化 Go 接口类型?
给定以下情况:
type Foo struct {
Td ThingDoer
// ... other stuff
}
type ThingDoer interface {
doThing()
}
type doerA struct {
AGuts string
}
func (a doerA) doThing() {}
type doerB struct {
BGuts string
}
func (b doerB) doThing() {}
foo < / code>是否有首选的序列化 /次要化策略?
附加,例如,元帅
函数doera
和doerb
满足序列化,但是foo.unmarshaljson
有效地是有效的Stuck:不知道提供的JSON是Doera还是Doerb类型。
编辑:链接的“类似”问题解决了此问题中概述的特定非解决示例。这个问题是询问存在优雅解决方案的存在。
Given the following:
type Foo struct {
Td ThingDoer
// ... other stuff
}
type ThingDoer interface {
doThing()
}
type doerA struct {
AGuts string
}
func (a doerA) doThing() {}
type doerB struct {
BGuts string
}
func (b doerB) doThing() {}
is there a preferred serialization / deserialization strategy for Foo
?
Attaching, eg, a MarshalJSON
function onto doerA
and doerB
satisfies the serialization, but then Foo.UnmarshalJSON
is effectively stuck: it can't know in advance whether the supplied JSON is of doerA or doerB type.
Edit: The linked "similar" question addresses the specific non-solution example outlined in this question. This question is asking about the existence of a graceful solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
想象一下,您有一个结构 Foo,其中包含一个或多个使用接口类型的字段。
假设您有一个具有两种可能结构的界面 Bar:Baz 和 Bam。
您可以定义辅助类型(FooConf),无需任何接口。仅具体类型。
该结构可能有一个方法
Build() Foo
,它将根据每种情况选择正确的类型。为了能够定义具体类型,您可以定义签名。例如,额外的字段“类型”(baz 或 bam)。
您只需要确保每种类型都可以一致地编组/解组。
Imagine you have an structure Foo with one or more fields using interface types.
Lets say you have an interface Bar with two possible structures: Baz and Bam.
You can define auxiliary type (FooConf), without any interface. Only concrete types.
This structure may have a method
Build() Foo
that will choose the right type on each case.To be possible define what is the concrete type you can define a signature. For instance an extra field “type” (baz or bam).
You just need to be sure about each type can marshal/unmarshal with consistency.