github.com/mattn/anko@v0.1.10/vm/vmConvertToXNotGo112.go (about) 1 // +build !go1.12 2 3 package vm 4 5 import ( 6 "reflect" 7 ) 8 9 // convertMap trys to covert the reflect.Value map to the map reflect.Type 10 func convertMap(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { 11 rtKey := rt.Key() 12 rtElem := rt.Elem() 13 14 // create new map 15 // note creating slice as work around to create map 16 // just doing MakeMap can give incorrect type for defined types 17 newMap := reflect.MakeSlice(reflect.SliceOf(rt), 0, 1) 18 newMap = reflect.Append(newMap, reflect.MakeMap(reflect.MapOf(rtKey, rtElem))).Index(0) 19 20 // copy keys to new map 21 // Before Go 1.12 the only way to do this is to get all the keys. 22 // Note this is costly for large maps. 23 mapKeys := rv.MapKeys() 24 for i := 0; i < len(mapKeys); i++ { 25 newKey, err := convertReflectValueToType(mapKeys[i], rtKey) 26 if err != nil { 27 return rv, err 28 } 29 value := rv.MapIndex(mapKeys[i]) 30 value, err = convertReflectValueToType(value, rtElem) 31 if err != nil { 32 return rv, err 33 } 34 newMap.SetMapIndex(newKey, value) 35 } 36 37 return newMap, nil 38 }