多结构切换? [英] Multiple Struct switch?

查看:16
本文介绍了多结构切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个接收两种不同格式的 json 数据的应用程序.

f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`

我有一个与每种类型相关联的结构:

type F1 struct {col1 字符串col2 字符串}输入 F2 结构 {col3 字符串col4 字符串}

假设我使用 encoding/json 库将原始 json 数据转换为结构体:输入点{点类型字符串数据 json.RawMessage}

如何仅通过知道点类型将数据解码为合适的结构?

我正在尝试类似的东西:

func getType(pointType string) interface{} {切换点类型{案例f1":变量 p F1回报&p案例f2":变量 p F2回报&p}返回零}

这是行不通的,因为返回的值是一个接口,而不是正确的结构类型.我怎样才能使这种开关结构选择工作?

这是一个非工作示例

解决方案

您可以类型切换 在你的方法返回的接口上:

switch ps := parsedStruct.(type) {案例*F1:log.Println(ps.Col1)案例*F2:log.Println(ps.Col3)}

..等等.请记住,要使 encoding/json 包正确解码(通过反射),您的字段需要导出(大写首字母).

工作示例:http://play.golang.org/p/8Ujc2CjIj8>

Let's say I have an application that receives json data in two different formats.

f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`

And I have a struct associated to each type:

type F1 struct {
  col1 string
  col2 string
}

type F2 struct {
  col3 string
  col4 string
}

Assuming that I use the encoding/json library to turn the raw json data into the struct: type Point { pointtype string data json.RawMessage }

How can I decode the data into the appropiate struct just by knowing the pointtype?

I was trying something along the lines of :

func getType(pointType string) interface{} {
    switch pointType {
    case "f1":
        var p F1
        return &p
    case "f2":
        var p F2
        return &p
    }
    return nil
}

Which is not working because the returned value is an interface, not the proper struct type. How can I make this kind of switch struct selection work?

here is a non working example

解决方案

You can type switch on the interface returned from your method:

switch ps := parsedStruct.(type) {
    case *F1:
        log.Println(ps.Col1)
    case *F2:
        log.Println(ps.Col3)
}

..etc. Remember, for the encoding/json package to decode properly (via reflection), your fields need to be exported (uppercase first letter).

Working sample: http://play.golang.org/p/8Ujc2CjIj8

这篇关于多结构切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆