首页 > 解决方案 > 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 ...这似乎可行,但这是最好的解决方案吗?

标签: go

解决方案


推荐阅读