structFunc.go 705 B

12345678910111213141516171819202122232425
  1. package util
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. /*
  7. 合并两个结构体的值,遍历结构体s1,若s1中某字段值为空,则将s2该字段的值赋给s1,否则不变
  8. 参数:interface{} -> &struct, 结构体指针
  9. 返回值:interface{} -> &struct, 结构体指针
  10. */
  11. func MergeStructValue(s1 interface{}, s2 interface{}) interface{} {
  12. v1 := reflect.ValueOf(s1).Elem()
  13. v2 := reflect.ValueOf(s2).Elem()
  14. for i := 0; i < v1.NumField(); i++ {
  15. field := v1.Field(i)
  16. name := v1.Type().Field(i).Name
  17. if field.Interface() == reflect.Zero(field.Type()).Interface() {
  18. fmt.Printf("%+v %+v", name, v1.Kind() == reflect.Ptr)
  19. v1.FieldByName(name).Set(v2.FieldByName(name))
  20. }
  21. }
  22. return v1
  23. }