我试图在Go中创建一个通用方法,该方法将填充struct来自的使用数据map[string]interface{}。例如,方法签名和用法可能类似于:
struct
map[string]interface{}
func FillStruct(data map[string]interface{}, result interface{}) { ... } type MyStruct struct { Name string Age int64 } myData := make(map[string]interface{}) myData["Name"] = "Tony" myData["Age"] = 23 result := &MyStruct{} FillStruct(myData, result) // result now has Name set to "Tony" and Age set to 23
我知道可以使用JSON作为中介来完成;还有另一种更有效的方法吗?
最简单的方法是使用https://github.com/mitchellh/mapstructure
import "github.com/mitchellh/mapstructure" mapstructure.Decode(myData, &result)
如果您想自己做,则可以执行以下操作:
http://play.golang.org/p/tN8mxT_V9h
func SetField(obj interface{}, name string, value interface{}) error { structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.FieldByName(name) if !structFieldValue.IsValid() { return fmt.Errorf("No such field: %s in obj", name) } if !structFieldValue.CanSet() { return fmt.Errorf("Cannot set %s field value", name) } structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("Provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } type MyStruct struct { Name string Age int64 } func (s *MyStruct) FillStruct(m map[string]interface{}) error { for k, v := range m { err := SetField(s, k, v) if err != nil { return err } } return nil } func main() { myData := make(map[string]interface{}) myData["Name"] = "Tony" myData["Age"] = int64(23) result := &MyStruct{} err := result.FillStruct(myData) if err != nil { fmt.Println(err) } fmt.Println(result) }