【问题标题】:Idiomatic way to represent one of/union in Go在 Go 中表示 of/union 之一的惯用方式
【发布时间】:2019-09-27 13:46:57
【问题描述】:

我希望实现一个可以是 Foo 或 Bar 的结构。

所以现在我有:

type Foo struct{}
type Bar struct{} 

// This is the end version consumed by my package
type Baz struct {
  Foo Foo `json:"foo,omitempty"`
  Bar Bar `json:"bar,omitempty"`
  // ... there are different members here
}

然后在我的内部函数中,我需要检查 Baz 是否包含 Foo 或 Bar 并以不同方式处理它们。

有没有一种惯用的方法来处理这个问题?现在我正在检查 Foo 的成员是否是默认值,但这感觉很hacky。

我考虑过让成员指针可以为空,然后我可以对照 nil 检查它们。

我错过了什么吗?

【问题讨论】:

    标签: go design-patterns


    【解决方案1】:

    您正在寻找algebraic data types。这个想法是定义一个您的“不同类型”实现的接口,并将该接口存储在预期的位置。

    【讨论】:

    • 这是一个简短的答案,但这篇文章的链接不仅仅是深入探讨它。 @EliBendersky 感谢这篇非常好的博文。
    猜你喜欢
    • 2013-01-03
    • 2013-08-08
    • 2019-06-28
    • 2012-08-11
    • 2018-02-04
    • 2019-03-27
    • 2012-06-12
    • 2021-04-15
    相关资源
    最近更新 更多