简体   繁体   English

go:接口的类型断言

[英]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. 我的意思是我想断言或强制转换,或者只是根据传入的数据strut更改结构的类型。

if sourceName variable would be type_x , than the type of deserializedData should be type_x , if type_y , than type_y . 如果sourceName变量将被type_x ,比的类型deserializedDatatype_x ,如果type_y ,比type_y How to set the variable deserializedData dynamicly for this ? 如何设置可变deserializedData动态地为这个?

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? 如何进行修改,以避免设置models.Noagg Model 。严格models.Noagg Model类型?

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:""} &main.Foo {富: “”}

Playground: http://play.golang.org/p/qeDA4cu5et 游乐场: http //play.golang.org/p/qeDA4cu5et

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM