Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Struct 多结构交换机?_Struct_Go - Fatal编程技术网

Struct 多结构交换机?

Struct 多结构交换机?,struct,go,Struct,Go,假设我有一个应用程序,它接收两种不同格式的json数据 f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}` f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}` 我有一个与每种类型关联的结构: type F1 struct { col1 string col2 string } type F2 struct { co

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

f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`
我有一个与每种类型关联的结构:

type F1 struct {
  col1 string
  col2 string
}

type F2 struct {
  col3 string
  col4 string
}
假设我使用
编码/json
库将原始json数据转换为结构: 类型点{ 点类型字符串 数据json.RawMessage }

我如何仅通过知道pointtype就将数据解码到appropiate结构中

我尝试了以下几点:

func getType(pointType string) interface{} {
    switch pointType {
    case "f1":
        var p F1
        return &p
    case "f2":
        var p F2
        return &p
    }
    return nil
}
因为返回的值是接口,而不是正确的结构类型,所以它不起作用。 如何使这种开关结构选择工作

您可以在方法返回的界面上:

switch ps := parsedStruct.(type) {
    case *F1:
        log.Println(ps.Col1)
    case *F2:
        log.Println(ps.Col3)
}
……等等。请记住,要使
encoding/json
包正确解码(通过反射),需要导出字段(大写首字母)


工作示例:

另一种方法是使用映射(由本机json包支持)

这里我假设每个数据属性(col1,col2…)都存在,但maps允许您检查它

package main

import "fmt"
import "encoding/json"

type myData struct {
    Pointtype string
    Data map[string]string
}

func (d *myData) PrintData() {
    if d.Pointtype == "type1" {
        fmt.Printf("type1 with: col1 = %v, col2 = %v\n", d.Data["col1"], d.Data["col2"])
    } else if d.Pointtype == "type2" {
        fmt.Printf("type2 with: col3 = %v, col4 = %v\n", d.Data["col3"], d.Data["col4"])
    } else {
        fmt.Printf("Unknown type: %v\n", d.Pointtype)
    }
}

func main() {
    f1 := `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
    f2 := `{"pointtype":"type2", "data":{"col3":"val3", "col4":"val4"}}`

    var d1 myData
    var d2 myData

    json.Unmarshal([]byte(f1), &d1)
    json.Unmarshal([]byte(f2), &d2)

    d1.PrintData()
    d2.PrintData()
}

另一种方法是使用映射(它由本机json包支持)。你有什么例子我可以查一下吗?我想就是这个了!。有没有一种方法可以返回正确的类型对象,而不必在每个开关盒内执行?没有。。那不行。您需要知道对象的类型。。因为他们有不同的领域。类型开关允许用户知道在给定上下文中访问的对象。如果您选择两个对象具有相同的字段名。。然后您可以让他们实现一个接口,其方法将值返回给您。除此之外,这是唯一的方法。当然,您的另一个选择是完全删除对象,并将其反序列化为
map[string]string
。不过,代码在眼睛上不会那么容易。。