【问题标题】:How to create a variable of dynamic type如何创建动态类型的变量
【发布时间】:2020-02-17 13:41:14
【问题描述】:

我可以创建一个“样本”类型的变量“模型”,如下所示:

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

var model Sample // created successfully

我能够成功创建它,因为我已经知道结构类型(示例)。

但是,当我尝试如下创建类似的变量“a”时,出现语法错误:

package main

import (
    "fmt"
    "reflect"
)

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

func test(m interface{}) {
    fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'

    var a reflect.TypeOf(m) // it throws - syntax error: unexpected ( at end of statement
}

func main() {

    var model Sample // I have created a model of type Sample
    model = Sample{Id: 1, Name: "MAK"}
    test(model)
}

请告知如何在 Go 中创建动态类型的变量。

【问题讨论】:

    标签: go struct go-reflect


    【解决方案1】:
    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type Sample struct {
        Id   int    `jsonapi:"attr,id,omitempty"`
        Name string `jsonapi:"attr,name,omitempty"`
    }
    
    func test(m interface{}) {
        fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'
    
        a, ok := m.(main.Sample)
        if ok {
            fmt.Println(a.Id)
        }
    }
    
    func main() {
    
        var model Sample // I have created a model of type Sample
        model = Sample{Id: 1, Name: "MAK"}
        test(model)
    }
    

    如果你想要更多的活力,你可以使用类型开关。而不是a, ok := m.(main.Sample),你做

    switch a := m.(type) {
        case main.Sample:
            fmt.Println("It's a %s", reflect.TypeOf(m))
        case default:
            fmt.Println("It's an unknown type")
    }
    

    【讨论】:

    • 我不想将类型断言作为 --> a, ok := m.(reflect.TypeOf(m)) 而不是 --> a, ok := m.(main.示例)
    • 这是不可能的,因为 Go 是一种静态类型的语言。所以你只能知道编译时存在的类型。 reflect 在编译时无法知道未知类型。有些人通过将任何类型的数据设为map[string]interface{} 来欺骗系统,因此您可以创建分层类型系统。查看encoding/json 包,看看它是如何完成的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2016-03-19
    • 2011-11-20
    • 2012-11-01
    • 2013-09-04
    • 2012-05-18
    相关资源
    最近更新 更多