我希望实现一个可以是 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 的成员是否是默认值,但这感觉很糟糕。
我考虑过让成员成为指针,这样它们就可以为空,然后我可以检查它们是否为 nil。
我是不是漏掉了什么?
最佳答案
您正在寻找 algebraic data types .这个想法是定义一个你的“不同类型”实现的接口(interface),并将该接口(interface)存储在它们需要的地方。
关于go - 在 Go 中表示其中一个/联合的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064237/