dongluxin6711 2016-02-15 12:25
浏览 25
已采纳

go:接口的类型断言

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?

  • 写回答

1条回答 默认 最新

  • dte8665 2016-02-15 13:00
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试