Altenrion
Altenrion

Reputation: 774

go: type assert of interface

I have a problem with making dynamic model of a struct. I mean that I want to assert or cast, or just change the type of struct according to the incoming data strut.

if sourceName variable would be type_x , than the type of deserializedData should be type_x, if type_y, than type_y. How to set the variable deserializedData dynamicly for this ?

I have this part in my code:

    .... 



  var cacheData []byte
    var deserializedData models.NoaggModel

    cache_err := cache.Get(string(string(sourceName) + "_" + string(t.Date)), &cacheData);
            if cache_err != nil {
                fmt.Println("cache_error: ", cache_err)
                panic("the cache is empty")
            }

            err2 := json.Unmarshal([]byte(cacheData), &deserializedData)
            if err2 == nil {
                fmt.Println("deserialized data: " + string(sourceName), deserializedData)
            }

            for _, chart := range charts {
                w.Name = chart.Name

            if err2 == nil {

                w.Data = countDataByName(sourceName, deserializedData, t.Request.Filters, string(chart.Name))
            }
            out <- w
        }
....

How to modify it, to avoid setting models.Noagg Model type in a strict way?

Upvotes: 0

Views: 949

Answers (1)

ANisus
ANisus

Reputation: 78105

Creating an instance of a type dynamically during runtime can be done using the reflect package. You can use a map to store the different types that you should be able to create:

Example:

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
    Foo string
}

type Bar struct {
    Bar int
}

func main() {
    var sourceTypes = map[string]reflect.Type{
        "foo": reflect.TypeOf(Foo{}),
        "bar": reflect.TypeOf(Bar{}),
    }

    sourceName := "foo"
    var deserializedData interface{}

    deserializedData = reflect.New(sourceTypes[sourceName]).Interface()
    fmt.Printf("%#v", deserializedData)
}

Output:

&main.Foo{Foo:""}

Playground: http://play.golang.org/p/qeDA4cu5et

Upvotes: 4

Related Questions