go - Golang 根据某些逻辑返回不同的结构并解组到该结构
问题描述
我有一个案例,我必须支持多个版本。每个都有不同的数据,所以我创建了 2 个结构。根据版本,我将返回 1 个结构。一旦我确定了哪个结构,我就会请求数据并解组到结构中。但是,由于该结构满足接口,我不认为解组工作正常。我总是得到结构的零值
package main
import (
"encoding/json"
"fmt"
)
// Ten300 ...
type Ten300 struct {
Map string `json:"map"`
Enabled string `json:"enabled"`
}
// Ten400 ...
type Ten400 struct {
Block1 int `json:"block_1"`
Block2 int `json:"block_2"`
}
// NET ...
type NET struct {
CMD Commands
S TenIft
}
// Commands ...
type Commands struct {
Get string
}
// TenIft ...
type TenIft interface {
Get(string) error
}
// Get ...
func (n *Ten300) Get(module string) error {
fmt.Println("Ten300", "Get()")
return nil
}
// Get ...
func (n *Ten400) Get(module string) error {
fmt.Println("Ten400", "Get()")
n.Block2 = 100
return nil
}
// TenGen easy to read fun type
type TenGen func() NET
// VersionSetup is a map of possible version
var VersionSetup = map[string]TenGen{
"3.0.0": func() NET {
return NET{
CMD: Commands{
Get: "getConfig",
},
S: &Ten300{},
}
},
"4.0.0": func() NET {
return NET{
CMD: Commands{
Get: "getSettings",
},
S: &Ten400{},
}
},
}
const input300 = `{
"map": "one",
"enabled": "two"
}`
const input400 = `{
"block_1": 1,
"block_2": 2
}`
// Setup ...
func (n *NET) Setup() error {
// This Switch is just to use hard coded data
var input string
switch n.S.(type) {
case *Ten400:
input = input400
case *Ten300:
input = input300
}
err := json.Unmarshal([]byte(input), n.S)
if err != nil {
fmt.Println("returning err:", err)
return err
}
fmt.Printf("n.s type: %T\nn.s value: %+v\n", n.S, n.S)
n.S.Get("xxx")
return nil
}
func main() {
version := "3.0.0"
if f, ok := VersionSetup[version]; ok {
net := f()
err := net.Setup()
if err != nil {
panic(err)
}
}
version = "4.0.0"
if f, ok := VersionSetup[version]; ok {
net := f()
err := net.Setup()
if err != nil {
panic(err)
}
}
}
添加了 go-playground ...这似乎可行,但这是最好的解决方案吗?
解决方案
推荐阅读
- java - 如何为 LiveData 查询 Room 数据库
在传递变量时 - postgresql - 无法使用 Docker 连接我的 postgres 数据库
- python - 如何为python程序跨平台设置内存限制?
- python - 在多线程 PyQt5 应用程序的异常中输入 pdb 时避免段错误?
- consistency - 哪些编译器为生成的 asm 代码提供保证(保证)?
- markdown - 在pandoc markdown的项目符号之间插入空行?
- java - 平方数的方法参数的困难
- api - 没有密码的xray rest api身份验证
- javascript - 在 Firestore 查询中获得重复的结果?
- python - 从树莓派发送数据