1 回答
TA贡献1851条经验 获得超3个赞
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")
}
- 1 回答
- 0 关注
- 132 浏览
添加回答
举报