是否有一种优雅的方法来反序列化 Go 接口类型?

发布于 2025-01-18 04:24:54 字数 538 浏览 4 评论 0原文

给定以下情况:

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>是否有首选的序列化 /次要化策略?

附加,例如,元帅函数doeradoerb满足序列化,但是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同尘 2025-01-25 04:24:54

想象一下,您有一个结构 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文