【发布时间】: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