例如,如果我有一个interface{}原来是一个map[string]map[int64][]int64或任何其他类型的地图的值,如何获得地图的密钥类型?或者更确切地说,如何将其转换为map[theKeyType]interface{}?
func Transverse(any interface{}) string {
res := ``
switch any.(type) {
case string:
return ``
case []byte:
return ``
case int, int64, int32:
return ``
case float32, float64:
return ``
case bool:
return ``
case map[int64]interface{}:
return ``
case map[string]interface{}:
return ``
case []interface{}:
return ``
default:
kind := reflect.TypeOf(any).Kind()
switch kind {
case reflect.Map:
// how to convert it to map[keyType]interface{} ?
}
return `` // handle other type
}
return ``
}
Run Code Online (Sandbox Code Playgroud)
获取密钥类型很简单:
reflect.TypeOf(any).Key()
Run Code Online (Sandbox Code Playgroud)
要进行整个转换,您需要创建一个类型的地图值,map[keyType]interface{}然后复制这些值.以下是如何完成此操作的工作示例:
package main
import (
"errors"
"fmt"
"reflect"
)
func InterfaceMap(i interface{}) (interface{}, error) {
// Get type
t := reflect.TypeOf(i)
switch t.Kind() {
case reflect.Map:
// Get the value of the provided map
v := reflect.ValueOf(i)
// The "only" way of making a reflect.Type with interface{}
it := reflect.TypeOf((*interface{})(nil)).Elem()
// Create the map of the specific type. Key type is t.Key(), and element type is it
m := reflect.MakeMap(reflect.MapOf(t.Key(), it))
// Copy values to new map
for _, mk := range v.MapKeys() {
m.SetMapIndex(mk, v.MapIndex(mk))
}
return m.Interface(), nil
}
return nil, errors.New("Unsupported type")
}
func main() {
foo := make(map[string]int)
foo["anisus"] = 42
bar, err := InterfaceMap(foo)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", bar.(map[string]interface{}))
}
Run Code Online (Sandbox Code Playgroud)
输出:
map[string]interface {}{"anisus":42}
Run Code Online (Sandbox Code Playgroud)
游乐场: http ://play.golang.org/p/tJTapGAs2b
| 归档时间: |
|
| 查看次数: |
944 次 |
| 最近记录: |