我希望了解哪种方法是解决以下问题的最合适的方法。
我有一个结构体,表示要作为JSON响应的一部分序列化的数据。此结构config
上的属性可以是三种可能的结构之一,然而,据我所知,表示此属性的唯一方法是使用类型interface{}
并让调用者类型断言该属性。
type Response struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
Config interface{} `json:"config"`
}
type ConfigOne struct {
SomeField string
}
type ConfigTwo struct {
SomeField int
}
type ConfigThree struct {
SomeField bool
}
然后,我可以使用New
风格的函数为我创建合适的实例:
func NewConfigTwo() *Response {
return &Response{
Field1: "hello",
Field2: 1,
Config: ConfigTwo{
SomeField: 22,
},
}
}
有没有更好的方法来用枚举类型的结构来表示一个字段?或者这是我能做的最好的了吗?
我非常感谢任何关于如何最好地实现这一点的清晰度或建议。
发布于 2019-05-03 20:50:30
从本质上讲,您在这里尝试实现一个代数数据类型。要扩展@mkopriva的评论,请查看此帖子:Go and algebraic data types。本质上,您将指定一个非空接口,以便所有可能的类型都实现一个方法,而其他类型“偶然”不满足该接口(而每个类型都实现interface{}
),然后使用类型切换。
类似于(未测试的):
type Response struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
Config Configable `json:"config"`
}
type Configable interface {
isConfig()
}
type ConfigOne struct {
SomeField string
}
func (ConfigOne) isConfig() {}
// ... and so on for other Config* types
https://stackoverflow.com/questions/55966674
复制相似问题