translate.go 620 B

12345678910111213141516171819202122232425262728
  1. package pkg
  2. import (
  3. "reflect"
  4. )
  5. func Translate(form, to interface{}) {
  6. fType := reflect.TypeOf(form)
  7. fValue := reflect.ValueOf(form)
  8. if fType.Kind() == reflect.Ptr {
  9. fType = fType.Elem()
  10. fValue = fValue.Elem()
  11. }
  12. tType := reflect.TypeOf(to)
  13. tValue := reflect.ValueOf(to)
  14. if tType.Kind() == reflect.Ptr {
  15. tType = tType.Elem()
  16. tValue = tValue.Elem()
  17. }
  18. for i := 0; i < fType.NumField(); i++ {
  19. for j := 0; j < tType.NumField(); j++ {
  20. if fType.Field(i).Name == tType.Field(j).Name &&
  21. fType.Field(i).Type.ConvertibleTo(tType.Field(j).Type) {
  22. tValue.Field(j).Set(fValue.Field(i))
  23. }
  24. }
  25. }
  26. }