Is the Golang switch multi-line?

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 structure associated with each type:

type F1 struct {
  col1 string
  col2 string
}

type F2 struct {
  col3 string
  col4 string
}

Assuming I am using a library encoding/jsonto turn json source data into struct: type Point {string of type pointtype json.RawMessage data}

How can I decode data in a suitable structure, just knowing the type of point?

I tried to do something like this:

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

Which does not work, because the return value is an interface, not the corresponding type of structure. How can I make this switch structure selection function?

here is a non-working example

+4
source share
2 answers

, :

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

.. .. , encoding/json ( ) ( ).

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

+4

( json).

, (col1, col2...) , .

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()
}

http://play.golang.org/p/5haKpG7MXg

+1

All Articles