golang: use reflect to get field's value from a interface{} to map[string]interface{}
If you want to get all fields' value from a interface{}
, you can use reflect.
First, use reflect.ValueOf
to get the value, then use .Elem()
get the element. Then you can get the value of a field by the field'name or index.
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 TestHuman(t *testing.T) {
var human Human
human = &Martian{
name: "Jack",
id: 1,
}
t.Log(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()
}
t.Log(data)
}
}