forked from go/golangs_learn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
779 B
54 lines
779 B
package main
|
|
|
|
import (
|
|
"github.com/golang/glog"
|
|
"reflect"
|
|
)
|
|
|
|
type Human interface {
|
|
Name() string
|
|
Type() string
|
|
}
|
|
|
|
type Martian struct {
|
|
name string
|
|
id int
|
|
}
|
|
|
|
func (m *Martian) Name() string {
|
|
return m.name
|
|
}
|
|
|
|
func (m *Martian) Type() string {
|
|
return "martian"
|
|
}
|
|
|
|
func main() {
|
|
var human Human
|
|
|
|
human = &Martian{
|
|
name: "Jack",
|
|
id: 1,
|
|
}
|
|
|
|
glog.Info(human.Name())
|
|
|
|
// convert interface{} to map[string]interface{}
|
|
data := map[string]interface{}{}
|
|
obj := reflect.ValueOf(human)
|
|
|
|
elem := obj.Elem()
|
|
|
|
if elem.Kind() == reflect.Struct {
|
|
id := elem.FieldByName("id")
|
|
if id.Kind() == reflect.Int {
|
|
data["id"] = id.Int()
|
|
}
|
|
|
|
name := elem.FieldByName("name")
|
|
if name.Kind() == reflect.String {
|
|
data["name"] = name.String()
|
|
}
|
|
glog.Info(data)
|
|
}
|
|
}
|
|
|