猿问

go:接口类型断言

我在制作结构的动态模型时遇到问题。我的意思是我想断言或强制转换,或者只是根据传入的数据支柱更改结构的类型。


如果sourceName变量是type_x,比类型deserializedData应该是type_x,如果type_y,比type_y。如何为此deserializedData动态设置变量?


我的代码中有这部分:


    .... 




  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

        }

....

如何修改它,避免models.Noagg Model以严格的方式设置类型?


眼眸繁星
浏览 167回答 1
1回答

桃花长相依

可以使用反射包在运行时动态创建类型的实例。您可以使用地图来存储您应该能够创建的不同类型:例子:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "reflect")type Foo struct {&nbsp; &nbsp; Foo string}type Bar struct {&nbsp; &nbsp; Bar int}func main() {&nbsp; &nbsp; var sourceTypes = map[string]reflect.Type{&nbsp; &nbsp; &nbsp; &nbsp; "foo": reflect.TypeOf(Foo{}),&nbsp; &nbsp; &nbsp; &nbsp; "bar": reflect.TypeOf(Bar{}),&nbsp; &nbsp; }&nbsp; &nbsp; sourceName := "foo"&nbsp; &nbsp; var deserializedData interface{}&nbsp; &nbsp; deserializedData = reflect.New(sourceTypes[sourceName]).Interface()&nbsp; &nbsp; fmt.Printf("%#v", deserializedData)}输出:&main.Foo{Foo:""}游乐场: http : //play.golang.org/p/qeDA4cu5et
随时随地看视频慕课网APP

相关分类

Go
我要回答