Go 通用结构体赋值

package main

import (
	"errors"
	"fmt"
	"reflect"
)

type cat struct{
	Name string
	Age  int
}

type mouse struct {
	name  string
	color string
}

func main() {
  tomcat := &cat{}
  fillBySettings(tomcat,map[string]interface{}{
  	"Name":"tom",
  	"Age":6,
  })

  fmt.Println(tomcat)

  defer func() {
  	if err := recover(); err != nil {
  		fmt.Println(err)
	}
  }()

  func() {
	  jerrymouse := &mouse{}
	  fillBySettings(jerrymouse,map[string]interface{}{
		  "name":"tom",
		  "color":"cyan",
	  })
	  fmt.Println(jerrymouse)
  }()
}

func fillBySettings(structPtr interface{}, settings map[string]interface{})error{
  if reflect.TypeOf(structPtr).Kind() != reflect.Ptr {
  	return errors.New("the first param is not a pointer")
  }

  if settings == nil {
  	return errors.New("settings is nil")
  }

  var (
  	field  reflect.StructField
  	ok     bool
  )

  for k, v := range settings {
  	if field, ok = (reflect.ValueOf(structPtr)).Elem().Type().FieldByName(k); !ok {
  		continue
	}
	if field.Type == reflect.TypeOf(v) {
		reflect.ValueOf(structPtr).Elem().FieldByName(k).Set(reflect.ValueOf(v))
	}
  }
  return nil
}


你可能感兴趣的:(Go,golang)