Golang 使用反射获取 struct 的值

对于指针指向的对象,使用 reflect.ValueOf(...).Elem(...).FieldByName(),否则,直接:reflect.ValueOf(...).FieldByName()


type Human struct {
    name string
    id   int
}

human := &Human{
    name: "Jack",
    id:   1,
}

obj := reflect.ValueOf(human)

// if it is a poiner, should use Elem.
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)
}