如何创建动态类型的变量

How to create a variable of dynamic type

我可以创建类型为 'Sample' 的变量 'model',如下所示:

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中创建动态类型的变量。

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")
}