vmConvertToXGo112.go 942 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // +build go1.12
  2. package vm
  3. import (
  4. "reflect"
  5. )
  6. // convertMap trys to covert the reflect.Value map to the map reflect.Type
  7. func convertMap(rv reflect.Value, rt reflect.Type) (reflect.Value, error) {
  8. rtKey := rt.Key()
  9. rtElem := rt.Elem()
  10. // create new map
  11. // note creating slice as work around to create map
  12. // just doing MakeMap can give incorrect type for defined types
  13. newMap := reflect.MakeSlice(reflect.SliceOf(rt), 0, 1)
  14. newMap = reflect.Append(newMap, reflect.MakeMap(reflect.MapOf(rtKey, rtElem))).Index(0)
  15. // copy keys to new map
  16. // For Go 1.12 and after can use MapRange
  17. mapIter := rv.MapRange()
  18. var value reflect.Value
  19. for mapIter.Next() {
  20. newKey, err := convertReflectValueToType(mapIter.Key(), rtKey)
  21. if err != nil {
  22. return rv, err
  23. }
  24. value, err = convertReflectValueToType(mapIter.Value(), rtElem)
  25. if err != nil {
  26. return rv, err
  27. }
  28. newMap.SetMapIndex(newKey, value)
  29. }
  30. return newMap, nil
  31. }